Abe*_*san 2 c arrays pointers file
我正在学习如何用 C 编写和读取文件,并且我使用此代码编写了一篇文本
\n FILE *f = fopen("testingText.txt", "w");\n char *text = "This is text1...";\n fwrite(text, sizeof(char), strlen(text), f );\n fclose(f);\nRun Code Online (Sandbox Code Playgroud)\n当我读取该文件的内容并使用此代码打印它时
\n FILE *f = fopen("testingText.txt", "r");\n fseek(f, 0, SEEK_END);\n unsigned int size = ftell(f);\n fseek(f , 0, SEEK_SET);\n char *content = (char *)malloc(size);\n\n fread(content, sizeof(char), size, f);\n printf("File content is...\\n%s", content);\n\n\n free(content);\n fclose(f);\nRun Code Online (Sandbox Code Playgroud)\n它给出了像这样奇怪的事情的结果
\n文件内容是...\n这是text1...Path=C:* \xe2\x94\xac#\xc3\xa6\xe2\x95\xa9e\xc3\xb2 *
\n当我再次运行代码时,它给出了不同的奇怪的东西。
\n文件中没有空终止符,因此您需要在打印从文件中读取的内容之前手动添加空终止符。
例子:
char *content = malloc(size + 1); // +1 for the null terminator
size_t chars_read = fread(content, 1, size, f); // store the returned value
content[chars_read] = '\0'; // add null terminator
printf("File content is...\n%s\n", content); // now ok to print
Run Code Online (Sandbox Code Playgroud)