[英]Can not read all numbers from a txt file in C
我有一個在MPI中運行的程序。 盡管實際的問題只是程序的一部分,其中處理器0從txt文件讀取一些數字到一個動態數組中。 為了確定我已掃描到文件末尾,我使用文件指針並將結果除以4(這是每個int所需的字節數),並且應具有正確的大小來分配內存。 問題是,它無法按預期工作,並且最終只有一半大小,因此我將讀取一半文件,並且該程序將不正確。
我嘗試格式化文件中的數字,或者假設這是這種性質的問題,但是什么也沒有。
我的Data.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);
不要給你文件中的數字數量
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.