Scan whole line from file in C Programming

孤街醉人 提交于 2019-12-05 14:36:34

You can use getline(3). It allocates memory on your behalf, which you should free when you are finished reading lines.

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.

  1. 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.

  2. 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.

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

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!