就像我在标题中所说的,我不知道如何在 C 中打印 .txt 文件的所有内容。 这是我所做的一个不完整的函数:
void
print_from_file(items_t *ptr,char filemane[25]){
char *string_temp;
FILE *fptr;
fptr=fopen(filemane, "r");
if(fptr){
while(!feof(fptr)){
string_temp=malloc(sizeof(char*));
fscanf(fptr,"\n %[a-z | A-Z | 0-9/,.€#*]",string_temp);
printf("%s\n",string_temp);
string_temp=NULL;
}
}
fclose(fptr);
}
我非常确定 fscanf 中存在错误,因为有时它不会退出循环。
有人可以纠正这个吗?
最佳答案
您使用的 malloc
是错误的。将 sizeof(char*)
传递给 malloc
意味着您只为字符串提供保存指向字符(数组)的指针所需的内存量。因此,目前,通过写入尚未分配的内存,您会出现未定义的行为。强烈建议对文件长度进行检查,否则请确保您不会在字符串中写入比分配给它的更多内容。
相反,做这样的事情:
string_temp=malloc(100*sizeof(char)); // Enough space for 99 characters (99 chars + '\0' terminator)
关于c - 如何将 .txt 文件的内容打印为字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38074952/