вы пишете число в виде текста:
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");
кажется логичным, что для похоже на значение в main для чтения значений из файла и печати их на 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