Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Skip remainder of line with fscanf in C

Tags:

c

scanf

I'm reading in a file and after reading in a number, I want to skip to remaining part of that line. An example of a file is this

2 This part should be skipped
10 and also this should be skipped
other part of the file

At the moment I solve this by using this loop:

char c = '\0';
while(c!='\n') fscanf(f, "%c", &c);

I was however wondering whether there isn't a better way of doing this. I tried this, but for some reason it isn't working:

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

I would have expected this to read everything up to the new line and then also read the new line. I don't need the content, so I use the * operator. However, when I use this command nothing happens. The cursor isn't moved.

like image 781
nvcleemp Avatar asked Oct 29 '25 17:10

nvcleemp


1 Answers

I suggest you to use fgets() and then sscanf() to read the number. scanf() function is prone to errors and you can quite easily get the format string wrong which may seem to work for most cases and fail unexpectedly for some cases when you find it doesn't handle some specific input formats.

A quick search for scanf() problems on SO would show how often people get it wrong and run into problems when using scanf().

Instead fgets() + sscanf() gives would give you better control and you know for sure you have read one line and you can process the line you read to read integer out it:

char line[1024];


while(fgets(line, sizeof line, fp) ) {

   if( sscanf(line, "%d", &num) == 1 ) 
   {
    /* number found at the beginning */
   }
   else
   {
    /* Any message you want to show if number not found and 
     move on the next line */
   }
}

You may want to change how you read num from line depending on the format of lines in the file. But in your case, it seems the integer is either located at first or not present at all. So the above will work fine.

like image 193
P.P Avatar answered Oct 31 '25 07:10

P.P



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!