Norman Norman - 10 months ago 77
C Question

NULL Terminator in text files

I am creating a program that reads in the contents of a text file through the command line, character by character.

Is the NULL value automatically inserted or do I have to add it to the text file manually?

Answer Source

Text files do not need to have a terminator on modern platforms. (On some legacy platforms they did have one, but I doubt it is the case here.) You almost certainly should not write a terminator into the file, as it may cause problems with programs that do not expect one. The end of file serves as a terminator when reading.

Text strings in C are arrays of characters terminated by a zero, aka the null character, mnemonic NUL (with one L, and it is not the same thing as NULL in C). When creating strings, you do need to terminate them correctly. Functions returning strings, including ones that read them from files (e.g., fgets), terminate them for you.