Enjoy coding
Enjoy coding

Reputation: 4366

How to know new line character in fscanf?

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.

Upvotes: 1

Views: 18724

Answers (2)

Jonathan Leffler
Jonathan Leffler

Reputation: 755094

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.

Upvotes: 1

AProgrammer
AProgrammer

Reputation: 52334

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.

Upvotes: 2

Related Questions