【问题标题】:C programming, reading from file error?C编程,从文件读取错误?
【发布时间】:2015-05-11 08:52:08
【问题描述】:

我的代码没有在while 循环的第二遍以及任何后续遍中将文本文件数据放入line。我确定这是一个愚蠢的错误,但我找不到它。

 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>

 FILE *fr;
 char *line,*word,*vali;
 ssize_t read;
 int i=0,sum=0,len =0,flag=0;
 const char delim[2]=" ";


 int main(int argc, char* argv[])
 {

     line = (char *)malloc(sizeof(&len)); 
     word = (char *)malloc(sizeof(&len));
     vali = (char *)malloc(sizeof(&len));

     fr = fopen(argv[1], "r");
     if(fr==NULL)
     {
         exit(EXIT_FAILURE);
     }
     while ((read = getline(&line, &len, fr)) != -1)
     {
         printf("line is %s\n", line );
         fscanf(fr,"%s%*[^\n]",word);           

         printf("%s ", word);
         vali=strtok(line, delim);
         while(vali != NULL)
         {
             sum=sum+atoi(vali);
             vali = strtok(NULL, delim);
         }
         printf("%d\n", sum);
         sum=0;
         vali=" ";
         len = strlen(line);
    }
    fclose(fr);
    if (line)
        free(line);
    return 0;
 }

【问题讨论】:

  • malloc(sizeof(&amp;len))。这看起来不正确。 len 是什么?看起来您只为指针分配空间。
  • len 定义和初始化为什么?
  • 显示完整的程序以及文件的内容。另外,正确缩进代码。
  • 标准警告:请do not castmalloc()C 中的家人的返回值。
  • lenlinewordvali 定义为什么?我们可以假设一些东西并进行修复,但是这不是这样的。请确保你放了可以编译的代码。

标签: c file pointers


【解决方案1】:

如果 len 是包含第一行所需长度的整数类型,则:

    &len

具有指向整数的类型,并且

    sizeof(&len)

返回指针的大小(在大多数 64 位系统上为 8 字节)和

    malloc(sizeof(&len))

仅分配 8 个字节的内存(或系统上的任何指针大小)。

这可能至少是问题的一部分。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-21
    • 1970-01-01
    • 2012-11-14
    相关资源
    最近更新 更多