Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is only fgets() best avoided in binary mode?

Tags:

c

character

Wikipedia says:

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

Is only fgets() best avoided in binary mode? How about other C library functions for reading files?

Thanks.

like image 760
Tim Avatar asked Sep 13 '14 23:09

Tim


Video Answer


1 Answers

fgets() reads a line of text, terminated by a single '\n' newline character (or a partial line if the next input line is longer than the buffer you're using).

When used on a text stream, an actual end-of-line marker, however it's represented, is converted to a single '\n' character, so fgets() will work as expected.

fgets() is far less likely to be useful on a binary stream. It will still read characters up to the end of the buffer or up to the first '\n' byte, whichever appears first. If that happens to be what you want to do, there's no particular reason not to use fgets().

The contents of a binary file have whatever meaning you assign to them. If a given binary file uses '\n' as a delimiter -- whether that happens to be the system's end-of-line marker for text files or not -- then fgets() will probably work.

But if you have a binary file with records(?) marked by '\n' characters, I have to wonder why it wasn't a text file in the first place.

fgets() is intended to be used to read lines from a text stream, but the way it works is rigorously defined by the C standard. It's defined to work as if by repeatedly calling fgetc().

If it happens to be useful for something else, feel free to use it. But any slight change in your requirements, like using a character other than '\n' as the delimiter, is likely to mean that fgets() will no longer work.

Just for the sake of clarity, you're probably better of writing a custom function that does what you want with binary input.

like image 139
Keith Thompson Avatar answered Sep 30 '22 05:09

Keith Thompson