【问题标题】:How can I print as strings the content of a .txt file?如何将 .txt 文件的内容打印为字符串?
【发布时间】:2016-06-28 11:26:13
【问题描述】:

就像我在标题中所说,我不知道如何在 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 中存在错误,因为有时它不会退出循环。

谁能更正一下?

【问题讨论】:

  • 你的string_temp=malloc(sizeof(char*)); 你正在为你的string_temp分配一个char指针大小的内存。 malloc 本身返回一个指针。

标签: c string file pointers


【解决方案1】:

你用错了malloc。将sizeof(char*) 传递给malloc 意味着您只为字符串提供了保存指向字符(数组)的指针所需的内存量。因此,目前,通过写入尚未分配的内存,您有未定义的行为。还强烈建议对文件长度执行检查,否则请确保不要在分配给它的字符串中写入更多内容。

相反,请执行以下操作:

    string_temp=malloc(100*sizeof(char)); // Enough space for 99 characters (99 chars + '\0' terminator)

【讨论】:

  • 谢谢你,我刚刚解决了这个问题!但它不会退出while循环
【解决方案2】:

您的代码中有几处需要修复。 首先,您应该经常检查文件是否已正确打开。

例子:

FILE *fp; //file pointer

if((fp = fopen("file.txt", "r") == NULL) {    //check opening

printf("Could not open file");  //or use perror()

exit(0); 

}

另外,请记住 scanf() 和 fscanf() 返回它们已读取的元素数。因此,例如,如果您一次扫描文件一个字,您可以通过循环 while fscanf(..) == 1 来简化程序。

作为最后一点,请记住正确分配动态内存。 您不想根据指向 char 大小的指针分配内存,实际上,您会想为字符串的每个字符分配 1 个字节,为终止符分配 + 1。

例子:

char name[55];
char * name2;

//To make them of the same size:

name2 = malloc(sizeof(*char)); **WRONG**
name2 = malloc(sizeof(char) * 55); //OK

【讨论】:

  • 感谢您的回答,现在我知道我正在为指针分配内存,而不是为字符串分配内存。我已经使用 if(fptr){ 检查文件是否已正确打开
  • 你知道while循环有什么问题吗?因为它没有退出循环
猜你喜欢
  • 1970-01-01
  • 2018-09-27
  • 2011-05-04
  • 2021-10-26
  • 1970-01-01
  • 1970-01-01
  • 2019-02-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多