HONDDAACCORD HONDDAACCORD - 7 days ago 6
C Question

c initializing array from file makes first element -1

I'm on ubuntu - codeblocks.
I was stuck in a more complex file reading task, so created the simplest test, and it throwed this weird "error" at me.

I have 2 global variables for the sake of simplicity

int a[20];
int row=20;


a function to initialize the array from a file

void load_file(char* filename) {
int i;
FILE* f;

f=fopen(filename, "r");

for (i=0; i<row; i++)
fscanf(f, "%d", &a[i]);

fclose(f);
}


another function to save the array to (the same) file

void save_file(char* filename) {
int i;
FILE* f;

f=fopen(filename, "w");

for (i=0; i<row; i++)
fprintf(f, "%d", a[i]);

fclose(f);
}


and because I really don't know what can be the problem here are the other two functions existing in the program:

void print_a() {
int i;
for (i=0; i<row; i++)
printf("%d ", a[i]);
printf("\n");
}

void init_a(int val) {
int i;
for (i=0; i<row; i++)
a[i]=val;
}


and here is the main:

int main(){

init_a(2);
print_a();
init_a(5);
save_file("a.txt");
load_file("a.txt");
print_a();


return 0;
}


the output of the program is:

2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
-1 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5


So the "error" is that after loading the file, the first element in the array is initialized with -1, while in the file there are only 20 5s.
I really have no clue, thanks for any help.

Answer

The problem is that your a.txt looks like this:

55555555555555555555

so when you try to read it again, it does not look like 20 integers. It looks like one very big number which is too big for an integer.

Add a space between each integer when printing to the file. Like this:

void save_file(char* filename) {
    int i;
    FILE* f;

    f=fopen(filename, "w");

    for (i=0; i<row; i++)
        fprintf(f, "%d ", a[i]);
              //      ^ notice

    fclose(f);
}

Besides that you should always check return values from fopen and fscanf