c - 如何将 .txt 文件的内容打印为字符串?

标签 c string file pointers

就像我在标题中所说的,我不知道如何在 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/

相关文章:

php - 在 php 中格式化带或不带前导零的日期

c - 搜索哈希表不起作用,for 循环不在 c 中执行

c - 通过 arduino 的 ENC28J60 模块发布 JSON 时出现奇怪的行为

c++ - 使用 std::string 时为 "error: no match for ‘operator<<"

java - BufferedReader 从未关闭,但文件能够删除

eclipse - 如何从 Eclipse 中的文件搜索中排除 .class 文件?

c - 在c中的文件中逐行搜索

c - 什么是典型的按键持续时间

c - 结构成员 - 地址重叠

java - 为什么substring()方法是substring(起始索引(含),结束索引(不含))