简体   繁体   English

无法从C中的txt文件读取所有数字

[英]Can not read all numbers from a txt file in C

I have a program that runs in MPI. 我有一个在MPI中运行的程序。 Though the actual problem is just a part of the program where Processor 0 reads from a txt file some numbers into a dynamic array. 尽管实际的问题只是程序的一部分,其中处理器0从txt文件读取一些数字到一个动态数组中。 To identify that I scan to the end of the file, I'm using the file pointer and divide the result with 4 (which is the number of bytes every int needs) and should have the right size to allocate the memory. 为了确定我已扫描到文件末尾,我使用文件指针并将结果除以4(这是每个int所需的字节数),并且应具有正确的大小来分配内存。 Problem is, that it does not work as intented and end up with half the size so I will read half the file and the program will not be correct. 问题是,它无法按预期工作,并且最终只有一半大小,因此我将读取一半文件,并且该程序将不正确。

I have tried to format the numbers in the file alternatively assuming that it was a problem of this nature but nothing. 我尝试格式化文件中的数字,或者假设这是这种性质的问题,但是什么也没有。

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

The section of the code that reads from the file: 从文件读取的代码部分:

           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;

The expected output should be an array with 12 elements such as the the numbers of the file. 预期的输出应该是一个包含12个元素的数组,例如文件的编号。

The actual output is an array with 6 elements until number 6 so half the actual size. 实际输出是一个包含6个元素的数组,直到第6个元素为实际大小的一半。

your file contains numbers in ascii, you cannot compare the size of the file with something based on sizeof(int) 您的文件包含ascii中的数字,您无法将文件的大小与基于sizeof(int)

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

do not give you the number of numbers in the file 不要给你文件中的数字数量

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

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