[英]Reading from binary file in C after saving
我正在嘗試讀取我創建的二進制文件。 打印無效,並且打印編號設置為(354),甚至在文件中也沒有。 我很樂意為我的問題提供幫助。
#include <stdio.h>
#include <stdlib.h>
int test();
int main(void) {
FILE *f;
f = fopen("nums.bin", "wb");
srand(40);
for(int i = 0; i<20; i++)
fprintf(f, "%d ", rand()%1000);
printf("Numbers saved to file.\n");
fclose(f);
test();
return 0;
}
int test() {
FILE *f;
int i=0;
printf("The numbers in the file are...\n");
f = fopen("nums.bin", "rb");
fread(&i, sizeof(i), 2, f);
printf("%d", rand()%1000);
return 0;
}
其他所有內容均按預期工作(文件中的數字與我希望的數字相同,等等)。 從文件中打印出來有點問題。 謝謝
您將數字寫為文本:
fprintf(f, "%d ", rand()%1000);
但您將數字讀為二進制
fread(&i, sizeof(i), 1, f);
這是不兼容的。
如果使用該fprintf進行編寫,則必須使用fscanf或等效的格式為“%d”的文件進行讀取,例如在編寫時。
否則就讀fread(&i, sizeof(i), 1, f);
你必須這樣寫:
int n = rand()%1000;
fwrite(&n, sizeof(n), 1, f);
除此之外,您的代碼中有些奇怪:
printf("The numbers in the file are...\n");
...
fread(&i, sizeof(i), 2, f);
printf("%d", rand()%1000);
因此,您讀取了一個數字(無論采用哪種方式),但沒有打印,而是打印了一個隨機值,為什么不打印i ?
在printf("The numbers in the file are...\\n");
之后printf("The numbers in the file are...\\n");
它似乎邏輯到了一個類似主從文件中讀取值,並將其打印在stdout
用二進制寫/讀的建議:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void test();
int main(void)
{
FILE *f = fopen("nums.bin", "wb");
if (f == 0) {
puts("cannot open file to write in");
return -1;
}
srand(time(NULL)); /* practical way to have different values each time the program runs */
for (int i = 0; i<20; i++){
int n = rand()%1000;
printf("%d ", n); /* to check the read later */
fwrite(&n, sizeof(n), 1, f);
}
printf(" are saved to file.\n");
fclose(f);
test();
return 0;
}
void test() {
FILE *f = fopen("nums.bin", "rb");
if (f == 0) {
puts("cannot open file to read in");
return;
}
printf("The numbers in the file are :\n");
for (int i = 0; i<20; i++){
int n;
fread(&n, sizeof(n), 1, f);
printf("%d ", n);
}
putchar('\n');
fclose(f);
}
示例(值每次都會更改):
pi@raspberrypi:/tmp $ gcc -pedantic -Wall r.c
pi@raspberrypi:/tmp $ ./a.out
208 177 118 678 9 692 14 800 306 629 135 84 831 737 514 328 133 969 702 382 are saved to file.
The numbers in the file are :
208 177 118 678 9 692 14 800 306 629 135 84 831 737 514 328 133 969 702 382
您的隨機化初始化srand(40)
將不會影響您的隨機數的質量。 您通常應該使用srand(time(null))
東西來獲得更“隨機”的東西。
test
結束時,您的輸出將打印一個隨機數,而不是您之前讀取的整數。 另外,您正在讀取fread(&i, sizeof(i), 2, f);
行中的兩個整數fread(&i, sizeof(i), 2, f);
這將破壞您的堆棧。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.