19

I want to scan a file and skip a line of text before reading. I tried:

fscanf(pointer,"\n",&(*struct).test[i][j]);

But this syntax simply starts from the first line.

4 Answers 4

55

I was able to skip lines with scanf with the following instruction:

fscanf(config_file, "%*[^\n]\n");

The format string matches a line containing any character including spaces. The * in the format string means we are not interested in saving the line, but just in incrementing the file position.

Format string explanation:
% is the character which each scanf format string starts with;
* indicates to not put the found pattern anywhere (typically you save pattern found into parameters after the format string, in this case the parameter is NULL);
[^\n] means any character except newline;
\n means newline;

so the [^\n]\n means a full text line ending with newline.

Reference here.

3
  • 2
    '\n' is whitespace, it means any amount of any whitespace is consumed, not just single newline.
    – hyde
    Commented Oct 28, 2019 at 11:50
  • It should also be mentioned that the way fscanf is implemented it will read the whole line into the memory and then free it. Commented Mar 30, 2021 at 14:46
  • why not just "%*\n" instead?
    – user97662
    Commented Oct 12, 2022 at 4:14
17

fgets will get one line, and set the file pointer starting at the next line. Then, you can start reading what you wish after that first line.

char buffer[100];
fgets(buffer, 100, pointer);

It works as long as your first line is less than 100 characters long. Otherwise, you must check and loop.

0
14

It's not clear what are you trying to store your data into so it's not easy to guess an answer, by the way you could just skip bytes until you go over a \n:

FILE *in = fopen("file.txt", "r");

Then you can either skip a whole line with fgets but it is unsafe (because you will need to estimate the length of the line a priori), otherwise use fgetc:

char c;
do {
  c = fgetc(in);
} while (c != '\n');

Finally you should have format specifiers inside your fscanf to actually parse data, like

fscanf(in, "%f", floatVariable);

you can refer here for specifiers.

1
  • using do { ... } while(); construct makes me happy
    – Erik
    Commented Aug 15 at 5:50
4

fgets would work here.

#define MAX_LINE_LENGTH 80

char buf[MAX_LINE_LENGTH];

/* skip the first line (pFile is the pointer to your file handle): */
fgets(buf, MAX_LINE_LENGTH, pFile);

/* now you can read the rest of your formatted lines */

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.