Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to skip a line when fscanning a text file?

Tags:

c

file

scanf

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.

like image 843
NLed Avatar asked May 09 '10 23:05

NLed


People also ask

How do I skip a line in Scanf?

I was able to skip lines with scanf with the following instruction: fscanf(config_file, "%*[^\n]\n");

How do I skip a line while reading a file?

Using readlines() method The primary function of the readlines() method is to read a file and then return a list. Since this function returns the list, we can repeat it. If the line number you are currently on is equal to the line number you wish to skip, you remove that line. If not, you consider it.

How do you skip to the next line in a text file in Python?

The new line character in Python is \n . It is used to indicate the end of a line of text. You can print strings without adding a new line with end = <character> , which <character> is the character that will be used to separate the lines.


2 Answers

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.

like image 198
Zac Avatar answered Sep 28 '22 02:09

Zac


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.

like image 34
WhirlWind Avatar answered Sep 28 '22 02:09

WhirlWind