问题
I was writing a program to input multiple lines from a file. the problem is i don't know the length of the lines, so i cant use fgets cause i need to give the size of the buffer and cant use fscanf cause it stops at a space token I saw a solution where he recommended using malloc and realloc for each character taken as input but i think there's an easier way and then i found someone suggesting using
fscanf(file,"%[^\n]",line);
Does anyone have a better solution or can someone explain how the above works?(i haven't tested it)
i use GCC Compiler, if that's needed
回答1:
You can use getline(3). It allocates memory on your behalf, which you should free when you are finished reading lines.
回答2:
and then i found someone suggesting using
fscanf(file,"%[^\n]",line);
That's practically an unsafe version of fgets(line, sizeof line, file);
. Don't do that.
If you don't know the file size, you have two options.
There's a
LINE_MAX
macro defined somewhere in the C library (AFAIK it's POSIX-only, but some implementations may have equivalents). It's a fair assumption that lines don't exceed that length.You can go the "read and realloc" way, but you don't have to
realloc()
for every character. A conventional solution to this problem is to exponentially expand the buffer size, i. e. always double the allocated memory when it's exhausted.
回答3:
A simple format specifier for scanf or fscanf follows this prototype
%specifier
specifiers
As we know d
is format specifier for integers Like this
[characters]
is Scanset
Any number of the characters specified between the brackets.
A dash (-) that is not the first character may produce non-portable behavior in some library implementations.
[^characters]
is
Negated scanset
Any number of characters none of them specified as characters between the brackets.
fscanf(file,"%[^\n]",line);
Read any characters till occurance of any charcter in Negated scanset
in this case newline character
As others suggested you can use getline() or fgets() and see example
回答4:
The line fscanf(file,"%[^\n]",line);
means that it will read anything other than \n
into line
. This should work in Linux and Windows, I think. But may not work in OS X format which use \r
to end a line.
来源:https://stackoverflow.com/questions/19410106/scan-whole-line-from-file-in-c-programming