Question

How to know that fscanf reached a new line \n in a file. I have been using my own functions for doing that. I know I can use fgets and then sscanf for my required pattern. But my requirements are not stable, some times I want to get TAB separated strings, some times new line separated strings and some times some special character separated strings. So if there is any way to know of new line from fscanf please help me. Or else any alternative ways are also welcome.

Thanks in advance.

Was it helpful?

Solution

fscanf(stream, "%42[^\n]", buffer);

is an equivalant of fgets(buffer, 42, stream). You can't replace the 42 by * to specify the buffer length in the argument (as you can do in printf), its meaning is to suppress the assignment. So

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

read upto (and included) the next end of line character.

Any conversion specifier other than [, c and n start by skipping whitespaces.

OTHER TIPS

Kernighan and Pike in the excellent book 'The Practice of Programming' show how to use sprintf() to create an appropriate format specifier including the length (similar to the examples in the answer by AProgrammer), and then use that in the call to scanf(). That way, you can also control the separators. Concerns about the 'inefficiency' of this approach are probably misguided - the alternatives are harder to get right.

That said, I most normally do not use the scanf() family of functions for file I/O; I get the data into a string with some sort of 'get line' routine, and then use the sscanf() family of functions to split it up - or other more specialized parsing code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top