'\0'字符为不可见字符,vim编辑器会使用‘^@’字符来显示'\0'字符。


看如下代码:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char    buf[] = "hello world!";
    FILE    * fp = NULL;
    size_t  ret = 0;
    
    fp = fopen("./test.txt", "a");
    if (fp == NULL) {
        printf("fopen error!\n");
        exit(-1);
    }

    ret = fwrite(buf, sizeof(char), sizeof(buf), fp);
    printf("ret = %zd\n", ret);
    
    fclose(fp);

    exit(0);
}

程序执行后,会在当前目录生成一个test.txt文本文件。使用vim编辑器打开,内容如下所示:

hello world!^@


问题出现在下面这段代码:

ret = fwrite(buf, sizeof(char), sizeof(buf), fp);

这条语句把'\0'字符写入到了test.txt文本文件中。

将这条语句改为下面的形式:

ret = fwrite(buf, sizeof(char), strlen(buf), fp);    // need <string.h>

则生成的文本文件中将不再包含'\0'字符。