fscanf无法从txt文件中读取数据

时间:2015-02-25 12:38:28

标签: c file-handling

我正在尝试使用ubuntu在eclipse上运行我的代码。

我使用fprintf将数据转储到一个txt文件中并使用fscanf读取该文件。我无法将这些值读入数据数组。

以下是我的代码:

#include <stdio.h>      /* printf, scanf, NULL */
#include <stdlib.h>     /* malloc, free, rand */

int main(){
    char* data;
    FILE *fp;
    size_t result;
    data = (char*) malloc (sizeof(char)*(1280*800));//Size of one frame
    if (data==NULL){
        printf("NOt able to allocate memory properly\n");
        exit (1);
    }
    fp = fopen ("\\home\\studinstru\\Desktop\\filedump.txt", "r");
    if(fp==NULL){
        printf("Error in creating dump file\n");
        exit (1);
    }
    for(int m = 0;m<1280;m++){
         for(int n = 0;n<800;n++){
         fscanf(fp,"%d/t",data[m*800 + n]);
     }
   }
    fclose(fp);
    return 0;
}

这是我的filedump.txt数据:

79  78  78  77  78  79  81  95
82  81  81  81  82  82  82  82
79  78  78  77  78  79  81  95
82  81  81  81  82  82  82  82
79  78  78  77  78  79  81  95
82  81  81  81  82  82  82  82 ....

你能告诉我这里有什么问题吗?

2 个答案:

答案 0 :(得分:1)

您的代码存在一些问题

  1. 您的fscanf()格式错误,并且您传递的是值而不是它的地址,您应该使用

    fscanf(fp, "%d", &data[n + 800 * m]);
    

    如果你的意思是"\t" whcih是tab字符,那么无论如何都不需要它并且传递值而不是它的地址是未定义的行为,因为fscanf()会将值视为指针,并且它不太可能指向有效的内存地址,而且,它是未初始化的,这是未定义行为的另一个原因。

  2. 您将data声明为char *data并将int存储在其中,这也是未定义的行为。

  3. 如果fscanf()失败,你必须检查fprintf(fp, "\n"); 的返回值,然后该值将被取消初始化,并且将再次显示未定义的行为,并且您将在过去结束时阅读文件,因为你永远不会知道你是否达到了它。

  4. 您正在写入文件并打开它进行阅读,这是

    sizeof(char)

    错了,你不需要它从文件中读取。

  5. Don't cast the result of malloc()虽然这不会导致问题,但它会提高代码的质量。

  6. 不要使用sizeof(char) == 1它会让您的代码更难阅读,因为标准要求fscanf()

  7. ,这完全没必要
  8. 您不需要嵌套循环来读取数据,因为数据的形状无关紧要,因为#include <stdio.h> /* printf, scanf, NULL */ #include <stdlib.h> /* malloc, free, rand */ int main() { FILE *fp; size_t index; int *data; data = malloc(1280 * 800); if (data == NULL) { printf("NOt able to allocate memory properly\n"); return 1; } fp = fopen("\\home\\studinstru\\Desktop\\filedump.txt", "r"); if (fp == NULL) { printf("Error in creating dump file\n"); free(data); return 2; } while (fscanf(fp, "%d", &data[index]) == 1) { fprintf(stdout, "%d ", data[index]); index += 1; if (index % 800 == 0) printf("\n"); } fclose(fp); return 0; } 会忽略所有空白字符。

    通过读取文件并使用计数器移动数组就足够了,最后您可以检查读取的值的数量,以验证数据的完整性。

  9. 这是您的代码的固定版本

    char *data

    注意:我建议使用编译器警告,它们有助于防止愚蠢的错误和其他一些错误,例如int并将"\\home\\studinstru\\Desktop\\filedump.txt"读入其中。

    另外,从你的文件路径/来看,你似乎在非Windows系统上,并且目录分隔符很可能是\而不是"/home/studinstru/Desktop/filedump.txt" ,所以正确的路径有是

    {{1}}

答案 1 :(得分:0)

替换

fscanf(fp,"%d/t",data[m*800 + n]);

fscanf(fp,"%d/t",&data[m*800 + n]);

fscanf()需要将目标变量的地址作为参数而不是变量本身。

我也不知道为什么这样做:

fprintf(fp,"\n");

相关问题