Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fscanf and newline character

Tags:

c

regex

file-io

I have fscanf to read lines of setting from a configuration file. Those settings have strictly predefined format which looks like

name1=option1;
name2=option2;
...

so basically I do

fscanf(configuration,"%[^=]=%[^;];",name,option);

where configuration is the file stream and name and option are programming buffers.

The problem is that the name buffer contains a newline character I don't want. Is there format specifier I've missed in the "[^...]" set to skip newline character? Anyway, can it be solved through format specifier ever?

BTW: Swallowing the newline character by writting this

"%[^=]=%[^;];\n"

is not elegent I think for that the newline character could repeat more than once anywhere.

like image 599
Yang Avatar asked Nov 04 '12 19:11

Yang


People also ask

Does fscanf read newline characters?

fscanf type specifiers String of characters. This will read subsequent characters until a whitespace is found (whitespace characters are considered to be blank, newline and tab).

Does fscanf ignore newline?

fscanf() is a very clunky interface for parsing files, it treats spaces, newlines and other whitespace characters the same, except for the %c and the %[ conversion specifiers.

How do I ignore a new line in scanf?

Use scanf(" %c", &c2); . This will solve your problem.

Does fgets include newline character?

The fgets() function stores the result in string and adds a NULL character (\0) to the end of the string. The string includes the newline character, if read.


3 Answers

Just add space at the end of the format string:

"%[^=]=%[^;]; "

This will eat all whitespace characters, including new-lines.

Quotation from cplusplus.com:

Whitespace character: the function will read and ignore any whitespace characters encountered before the next non-whitespace character (whitespace characters include spaces, newline and tab characters -- see isspace). A single whitespace in the format string validates any quantity of whitespace characters extracted from the stream (including none).

like image 78
Evgeny Kluev Avatar answered Oct 23 '22 16:10

Evgeny Kluev


An alternative is to use fgets() to read the entire line into a string, then use sscanf(). This has an advantage in debugging in that you can see exactly what data the function is working on.

like image 30
Clifford Avatar answered Oct 23 '22 16:10

Clifford


This will work:

fscanf(configuration,"%[^=]=%[^;];%[^\n]",name,option,dummy);

You will have to consume the new line character.Otherwise,the newline is left in the input stream.

like image 1
askmish Avatar answered Oct 23 '22 14:10

askmish