gpt4 book ai didi

arrays - 读取文件并在 C 中打印内容

转载 作者:行者123 更新时间:2023-12-05 08:45:58 24 4
gpt4 key购买 nike

我正在学习如何用 C 编写和读取文件,并且我使用这段代码编写了一段文本

 FILE *f = fopen("testingText.txt", "w");
char *text = "This is text1...";
fwrite(text, sizeof(char), strlen(text), f );
fclose(f);

当我读取此文件的内容并使用此代码打印时

 FILE *f = fopen("testingText.txt", "r");
fseek(f, 0, SEEK_END);
unsigned int size = ftell(f);
fseek(f , 0, SEEK_SET);
char *content = (char *)malloc(size);

fread(content, sizeof(char), size, f);
printf("File content is...\n%s", content);


free(content);
fclose(f);

它给出了这样奇怪的结果

文件内容是...这是 text1...Path=C:*┬#æ╩eò*

当我再次运行代码时,它给出了不同的奇怪的东西。

最佳答案

没有 null terminator在文件中,因此您需要在打印从文件中读取的内容之前手动添加它。

例子:

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

关于arrays - 读取文件并在 C 中打印内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70767909/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com