Home > Blockchain >  fgets() gets does not stop when it encounters a NUL. Under what circumstance will this be a problem?
fgets() gets does not stop when it encounters a NUL. Under what circumstance will this be a problem?

Time:08-15

I understand that when using fgets, the program will not stop when it encounters NUL, namely '\0'. However when will this a problem and needs to be manually addressed?

My main use case for fgets is to get it from user input (like a better version of scanf to allow reading white spaces.) I cannot think of a situation where a user will want to terminates his input by typing '\0'.

CodePudding user response:

Recall that text file input is usually lines: characters followed by a '\n' (expect maybe the last line). On reading text input, a null character is not special. It is not an alternate end-of-line. It is just another non-'\n' character.

It is functions like fgets(), fscanf() append a null character to the read buffer to denote the end of string. Now when code reads that string, is a null character a read one or the appended one?

If code uses fgets(), fscanf(), getchar(), etc. is not really the issue. The issue is how should code detect null characters and how to handle them.

Reading a null character from a text stream is uncommon, but not impossible. Null characters tend to reflect a problem more often than valid text data.

Reasons null characters exist in a text file

  1. The text file is a wide character text file, perhaps UTF16 when null characters are common. Code needs to read this file with fgetws() and related functions.

  2. The text file is a binary data one. Better to use fread().

  3. File is a text file, yet through error or nefarious intent, code has null characters. Usually best to detect, if possible, and exit working this file with an error message or status.

  4. Legitimate text file uncommonly using null characters. fgets() is not the best tool. Likely need crafted input functions or other extensions like getline().

How to detect?

fgets(): prefill buffer with non-zero input. See if the characters after the first null character are all the pre-fill value.

fscanf(): Read a line with some size like char buf[200]; fscanf(f, "9[^\n]%n", buf, &length); and use length for input length. Additional code needed to handle end-of-line, extra-long lines, 0 length lines, etc.

fgetc(): Build user code to read/handle as needed - tends to be slow.

How to handle?

In general, error out with a message or status.

If null characters are legitimate to this code's handling of text files, code needs to handle input, not as C strings, but as a buffer and length.

Good luck.

  • Related