Do the file input functions in standard C, like fgetc(), fgets() or fscanf(), have any problems with NUL (‘\0’) characters or treat them differently than other characters?
I was going to ask if I can use fgets() to read a line that may contain NUL characters, but I just realized that since that function NUL-terminates the input and doesn’t return the length in any other way, it’s worthless for that use anyway.
Can i use fgetc()/getc()/getchar() instead?
If what you’re reading is actually text, then you’re in somewhat of an awkward situation.
fgetswill read NULs just fine, store them in the buffer, and soldier on. Problem is, though, you’ve just read in what is no longer an NTBS (NUL-terminated byte string) as the C library typically expects, so most functions that expect a string will ignore everything after the first NUL. And you really don’t have a reliable way to get the length, sincefgetsdoesn’t return it to you andstrlenexpects a C string. (You could conceivably zero out the buffer each time and look for the last non-NUL char in order to get the length, but for short strings in big buffers, that’s kinda ugly.)If you’re dealing with binary, things are a lot simpler. You just
freadandfwritethe data, and all’s well. But if you want text with NULs in it, you’re probably going to end up needing your own read-a-line function that returns the length.