user3261349
user3261349

Reputation: 83

How to read in a specific line from an input file in C?

If I want to read in a specific line without knowing what exactly is in that line how would I do that using fscanf?

one \n
two \n
three \n
i want this line number four \n
five \n
six \n

How would I read in the 5th line in that input text file? Do I need to use a while loop or a for loop?

Upvotes: 0

Views: 1667

Answers (1)

Hamza
Hamza

Reputation: 1583

You can use any loop both work more or less same way

Here is something you can do

int ch, newlines = 0;
while ((ch = getc(fp)) != EOF) {
    if (ch == '\n') {
        newlines++;
        if (newlines == 5)
            break;
    }
}

Or you can use fgets because fgets places the "\n" (newline) at the end of the line

char line[100]; int newline=0;
          while ( fgets( line, 100, stdin ) != null ) 
            { 
              newline++;
              if(newline==5)
              {
                fprintf("The line is: %s\n", line); 
              }
            } 

Upvotes: 1

Related Questions