vim打开txt文件看到^@字符

'\0'是不可见字符,使用vim编辑器查看的文本文件中如果包含'\0'字符,vim会自动将'\0'字符转换为^@字符。

看下面的代码:

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 
 4 int main()
 5 {
 6     char        buf[] = "hello world!";
 7     FILE        * fp = NULL;
 8     size_t      ret = 0;
 9 
10     fp = fopen("./test.txt", "a");
11     if (fp == NULL) {
12         printf("fopen error!\n");
13         exit(-1);
14     }
15 
16     ret = fwrite(buf, sizeof(char), sizeof(buf), fp);
17     printf("ret = %zu\n", ret);    // %zu - size_t的格式控制符
18     fclose(fp);
19 
20     exit(0);
21 }

执行这个程序,输出:

ret = 13

说明有13个字符被写入到test.txt文件中。使用vim编辑器查看test.txt文件,会看到:

hello world!^@

说明buf字符串末尾的'\0'字符也被写入到了test.txt文件中。问题出现在下面这段代码:

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

将这段代码改成如下形式:

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

就可以解决这个问题。

原文地址:https://www.cnblogs.com/pyhou/p/6688450.html