繁体   English   中英

fscanf无法从txt文件读取数据

[英]fscanf fails to read data from txt file

我正在尝试使用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 ....

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

您的代码有很多问题

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

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

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

  2. 您将data声明为char *data并在其中存储int ,这也是Undefined Behavior。

  3. 您必须检查fscanf()的返回值,因为如果失败,则该值将未初始化,并且将再次出现“未定义行为”,并且您将要读取文件的末尾,因为您将永远不知道是否达到了。

  4. 您正在写入文件,然后将其打开以进行读取,这

     fprintf(fp, "\\n"); 

    是错误的,您不需要它从文件中读取。

  5. 尽管在这种情况下这不会引起问题,但是请不要malloc()的结果 ,它将提高代码的质量。

  6. 不要使用sizeof(char)这会使您的代码更难阅读,并且由于标准要求sizeof(char) == 1 ,因此完全没有必要。

  7. 您不需要嵌套循环即可读取数据,因为fscanf()忽略所有空白字符,因此数据的形状无关紧要。

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

这是您的代码的固定版本

#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;
}

注意 :我建议使用编译器警告,它们将帮助防止愚蠢的错误和其他一些错误,例如char *data并将int读入其中。

另外,从您的文件路径"\\\\home\\\\studinstru\\\\Desktop\\\\filedump.txt"看来,您使用的是非Windows系统,并且目录分隔符很可能是/而不是\\ ,因此正确的路径为成为

"/home/studinstru/Desktop/filedump.txt"

更换

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

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

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

另外我不明白为什么要这样做:

fprintf(fp,"\\n");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM