Best to avoid only fgets () in binary mode?

Wikipedia says:

The fgets () C library function is best avoided in binary mode, because any file not written with UNIX newline convention will be misread.

Best to avoid only fgets () in binary mode? How about other C library functions for reading files?



source to share

1 answer


reads a line of text ending with a single newline character '\n'

(or a partial line if the next line of input is larger than the buffer being used).

When used in a text stream, the actual end-of-line marker, however, is converted to a single character '\n'

, so fgets()

will work as expected.


much less useful for a binary stream. It will still read characters to the end of the buffer, or to the first byte '\n'

, whichever comes first. If that's what you want to do, there is no particular reason not to use it fgets()


The contents of the binary have whatever meaning you give them. If a given binary uses '\n'

as a delimiter - whether it will be an end-of-line marker for text files or not, then it fgets()

will probably work.

But if you have a binary file with entries (?) Marked with symbols '\n'

, I need to wonder why it was not a text file.


is designed to read lines from a text stream, but the way it works is strictly defined by the C standard. It is defined to work by repeating a call fgetc()


If it's useful for something else, feel free to use it. But any small change to your requirements, such as using a character other than '\n'

as a delimiter, most likely means it fgets()

will no longer work.

Just for clarity, you are probably better off writing a custom function that does what you want with binary input.



All Articles