Scanning an entire line from a file in C programming

I wrote a program to enter several lines from a file. the problem is that I don’t know the length of the lines, so I can’t use fgets because I need to specify the size of the buffer and not use fscanf because it stops at the space pointer I saw a solution in which he recommended using malloc and realloc for of every 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 this works? (I did not test it)

I use the GCC compiler if necessary

+4
source share
4 answers
+2

-, fscanf(file,"%[^\n]",line);

fgets(line, sizeof line, file);. .

, .

  • LINE_MAX, - C (AFAIK POSIX, ). , .

  • , realloc(). , .. . , .

+1

scanf fscanf

%specifier 

, d - .

[characters] Scanset , .   (-), , .

[^characters]  Negated scanset , .


fscanf(file,"%[^\n]",line);  

Read any characters before any character appears Negated scansetin this casenewline character


Like others, you can use getline()or fgets()and see an example

+1
source

String fscanf(file,"%[^\n]",line);means that it will read anything except \nto line. I think this should work on Linux and Windows. But it cannot work in OS X format, which it uses \rto complete the string.

0
source

All Articles