'\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>
就可以解決這個問題。
