Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is the null character a whitespace in C?

In the code below, isspace indicates that the null character is not a whitespace. Later in code the fwrite function writes a sequence of characters containing an intermediate and a final null character to a file.

The C17 standard indicates that the s conversion specifier "Matches a sequence of non-white-space characters." However, the fscanf at the end of the code only matches up to but not including the first null character.

Is there something in the standard that justifies this seemingly contradictory behavior? Are there bytes that are considered whitespace other than those indicated by isspace? If so, what are they? I put a \26 and a few other control characters in what I wrote to the file and fscanf read them just fine.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#include <stdio.h>
#include <ctype.h>

int main(void)
{
   int x = isspace('\0');
   char inBuf[40];
   char outBuf[] = "Hello\0world\n";
   FILE *fp = fopen("MyFile.txt", "w+b");
   fwrite(outBuf, 1, sizeof(outBuf), fp);
   fflush(fp);
   rewind(fp);
   fscanf(fp, "%s", inBuf);
}

>Solution :

However, the fscanf at the end of the code only matches up to but not including the first null character.

That is incorrect, as is demonstrated by the fact that the output of the following program is “"Hello", then "world".” fscanf reads the entire line up to the new-line character; it does not stop at the null character.

#include <string.h>
#include <stdio.h>
#include <ctype.h>

int main(void)
{
    char inBuf[40] = {0};
    char outBuf[] = "Hello\0world\n";
    FILE *fp = fopen("MyFile.txt", "w+b");
    fwrite(outBuf, 1, sizeof(outBuf), fp);
    fflush(fp);
    rewind(fp);
    fscanf(fp, "%s", inBuf);
    printf("\"%s\", then \"%s\".\n", inBuf, inBuf + strlen(inBuf) + 1);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading