Reputation: 161
I have a problem fetching lines from File Pointer using fscanf.
Let's say a want to fetch a line like this:
<123324><sport><DESCfddR><spor ds>
Fscanf fetch only this part:
<123324><sport><DESCfddR><spor
Does anybody know how to overcome this problem?
Thanks in advance.
Upvotes: 0
Views: 630
Reputation: 161
In conclusion,the best way to read lines which contain whitespaces is to use fgets:
fgets (currentLine, MAX_LENGTH , filePointer);
Using fscanf you are going to mess with a lot of problems.
Upvotes: 2
Reputation: 20244
You are probably using %s
in the fscanf
to read data. From the C11 standard,
7.21.6.2 The fscanf function
[...]
- The conversion specifiers and their meanings are:
[...]
s Matches a sequence of non-white-space characters. 286
[...]
So, %s
will stop scanning when it encounters a whitespace character or, if the length field is present, until the specified length or until a whitespace character, whichever occurs first.
How to fix this problem? Use a different format specifier:
fscanf(fp ," %[^\n]", buffer);
The above fscanf
skips all whitespace characters, if any, until the first non-whitespace character(space at the start) and then, %[^\n]
scans everything until a \n
character.
You can further improve security by using
fscanf(fp ," %M[^\n]", buffer);
Replace M
with the size of buffer
minus one(One space reserved for the NUL-terminator). It is the length modifier. Also checking the return value of fscanf
is a good idea.
Using fgets()
is a better way though.
Upvotes: 1