I have a very long array of ints (3,000,000+) that I want to store and be able to unpack quickly. At first, I wrote each int on a separate line in a text file, but that took rather long to unpack as the strings had to be converted back to ints. Then, someone suggested that I just write the array itself to the file, but when I read it back and print out the elements, it only prints zeroes. The code looked something like this:
#include <stdio.h>
#include <stdlib.h>
#define LENGTH 3000000
int main() {
FILE *f = fopen("file.txt", "w");
int *arr = malloc(LENGTH * sizeof(int));
/* initialization of arr not shown */
fwrite(arr, sizeof(int), LENGTH, f);
fclose(f);
free(arr);
return 0;
}
And then to unpack the data:
#include <stdio.h>
#include <stdlib.h>
#define LENGTH 3000000
int main() {
FILE *f = fopen("file.txt", "r");
int *arr = malloc(LENGTH * sizeof(int));
fread(arr, sizeof(int), LENGTH, f);
fclose(f);
for (int i = 0; i < LENGTH; ++i) {
printf("%d\n", arr[i]);
}
free(arr);
return 0;
}
But, as I said, it only prints zeroes. Why does this not work, and is there a more appropriate way of doing such a thing?
freadandfwriteto make sure you read / wrote the number of items you expected. Also, start by testing with a smaller array size.ftelland find out?