gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 14:43:01 26 4
gpt4 key购买 nike

我有一个在 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 个元素为止,因此是实际大小的一半。

最佳答案

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

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

不给您文件中的数字数量

关于无法从C中的txt文件中读取所有数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54171166/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com