gpt4 book ai didi

c - 读取文件时出现未知符号

转载 作者:行者123 更新时间:2023-11-30 18:43:42 24 4
gpt4 key购买 nike

我读取文件,但在文件末尾我得到未知符号:

int main()
{
char *buffer, ch;
int i = 0, size;
FILE *fp = fopen("file.txt", "r");
if(!fp){
printf("File not found!\n");
exit(1);
}
fseek(fp, 0, SEEK_END);
size = ftell(fp);
printf("%d\n", size);
fseek(fp, 0, SEEK_SET);
buffer = malloc(size * sizeof(*buffer));
while(((ch = fgetc(fp)) != NULL) && (i <= size)){
buffer[i++] = ch;
}
printf(buffer);
fclose(fp);
free(buffer);
getch();
return 0;
}

最佳答案

在打印之前,您需要在缓冲区末尾添加一个 null 字符:

while(((ch = fgetc(fp)) != NULL) && (i <= size)){
buffer[i++] = ch;
}
buffer[i] = 0; // add a null char at the end.
printf("%s",buffer); // print using %s format specifier.

关于c - 读取文件时出现未知符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2530098/

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