【问题标题】:Can not read all numbers from a txt file in C无法从 C 中的 txt 文件中读取所有数字
【发布时间】:2019-06-07 19:55:54
【问题描述】:

我有一个在 MPI 中运行的程序。虽然实际问题只是处理器 0 从 txt 文件中读取一些数字到动态数组中的程序的一部分。为了识别我扫描到文件末尾,我使用文件指针并将结果除以 4(这是每个 int 需要的字节数),并且应该具有正确的大小来分配内存。问题是,它没有按预期工作,最终大小只有一半,所以我将读取一半文件,程序将不正确。

我尝试格式化文件中的数字,或者假设这是这种性质的问题,但没有。

我的数据.txt: 1 2 3 4 5 6 7 8 9 10 11 12

从文件中读取的代码部分:

           fp = fopen("Data.txt", "r");
           if (fp == NULL) {
                fprintf(stderr, "Error while opening file.\n");
                MPI_Abort(newComm, 2);
            }

            fseek(fp, 0, SEEK_END);
            n = ftell(fp);
            n /= sizeof(int);
            printf("n = %d\n", n);
            fseek(fp, 0, SEEK_SET);

            workLoad = n / p;

            if (n % p != 0) {
                fprintf(stderr, "The number of elements in the file MOD the number of proccessors must equal zero.\n");
                MPI_Abort(newComm, 2);
            }

            arr = (int*)malloc(n * sizeof(int));
            if (arr == NULL) {
                fprintf(stderr, "Error in malloc!\n");
                MPI_Abort(newComm, 1);
            }

            for (i = 0; i < n; i++)
                fscanf(fp, "%d", arr + i);

            fclose(fp);

            printf("Numbers loaded from file.\n");
            break;

预期的输出应该是一个包含 12 个元素的数组,例如文件的编号。

实际输出是一个包含 6 个元素的数组,直到第 6 个元素是实际大小的一半。

【问题讨论】:

    标签: c file numbers


    【解决方案1】:

    您的文件包含 ascii 中的数字,您无法将文件的大小与基于 sizeof(int) 的内容进行比较

           fseek(fp, 0, SEEK_END);
            n = ftell(fp);
            n /= sizeof(int);
    

    不要给你文件中的数字个数

    【讨论】:

    • 感谢您的回答,我现在知道了。如果我要将文件更改为二进制文件,这是一个好的方向吗?
    • 我不知道你有什么要求。在您的代码中,您尝试知道要执行 malloc 多少个数字,然后加载这些数字,我认为您必须查看 realloc 才能看到您不需要知道在完成所有其余操作之前还有多少跨度>
    • 谢谢,我会看的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多