I am new to C programming and I am confused how to skip the first two lines in a file. I tried using fgets
and fscanf
, but I can't figured it out how to do it. Assume I have a file txt like this:
1 Username: Test
2 Password: 12345
3
4
So how can I start scan from line 3 and skip lines 1 and 2? Thank you.
CodePudding user response:
There are multiple ways to skip a line from a standard stream:
you can read a line with
fgets()
into achar
array and ignore it. This will effectively consume the line if the array if long enough.you can use
fscanf()
with cryptic conversion specifications:fscanf(fp, "%*[^\n]"); // consume bytes different from newline, if any fscanf(fp, "%*1[\n]"); // consume a single newline, if present
you can read and discard bytes with a simple loop:
int c; while ((c = getc(fp)) != EOF && c != '\n') continue;
To skip 2 lines, repeat the above code twice or better write a function int skip_line(FILE *fp)
with the third option, returning c
and call it twice.
#include <stdio.h>
// read and discard a line from stream fp, return EOF at end of file.
int skip_line(FILE *fp) {
int c;
while ((c = getc(fp)) != EOF && c != '\n')
continue;
return c;
}
CodePudding user response:
You can use the following code to skip two lines :
fscanf(fp,"%*[^\n]%*c%*[^\n]%*c");