Some systems allow a terminal user to enter NUL bytes by pressing Ctrl - @ . scanf()
then store this byte in the target array, but most likely will not consider this byte as a word delimiter, so parsing of the input will continue to the end of the file or the space character, such as a new line.
It is not possible to specify from the destination array if the NUL byte was saved after other characters, and also exactly how many other characters were read after this NUL byte. But if scanf()
returns 1
and msg
is of zero length, the only possibility is that the user entered a NUL byte after a possible empty sequence of whitespace characters.
This will also be the only way for fgets()
to return an empty string when passing the target array with a size greater than 1.
If the input is read from a file, and not from the terminal, there is always the possibility for a file to contain NUL bytes, and care should be taken to avoid undefined behavior if this happens. For example, here is a classic error:
char msg[1000]; if (fgets(msg, sizeof msg, stdin)) { int len = strlen(msg); if (msg[len - 1] == '\n') {
Also note that your code has flaws: the maximum number of characters to store at the destination should be 999
, not 1000
:
char msg[1000]; if (scanf("%999s",msg) == 1) { if (*msg == '\0') { printf("user entered a NUL byte\n"); } }
source share