So, i'm tring to write 9 numbers into a binary file and then read them from that file and print them to the screen, but for some reason it is not working and i can't figure out why.I've tried to look for the answer on the internet, but nothing seem to help. If someone could point out the maistake in my code (which is probably very obvious, but i'm a newbie in c), i would be extremly thankful. Here is the code:
int main()
{
FILE *f;
if(f=fopen("dat", "wb") == NULL){
return 1;
}
int c;
for(int i = 0; i < 9; i++){
c = fwrite(&i, sizeof(int), 1, f);
printf("%d",c); //it prints 0 every single time, as if nothing was written in the file
}
fclose(f);
if(f=fopen("dat", "rb+")==NULL){
return 1;
}
int a;
while(fread(&a, sizeof(int), 1, f)){
printf("%d\n", a);
}
fclose(f);
}
There is an issue about operator precedence.
Pay attention to the comparison and the assignment performed inside the if
statement:
if (f = fopen("dat", "wb") == NULL)
The comparison operator (==
) has a higher precedence than the assignment operator (=
). The code above is actually equivalent to:
if (f = (fopen("dat", "wb") == NULL))
That is, the result of the call to fopen()
is first being compared against NULL
and then the result of this comparison is assigned to f
.
What you actually want is:
if ((f = fopen("dat", "wb")) == NULL)
That is, first assign the result of fopen()
to f
and then perform the comparison against NULL
.
The same applies to your second call to fopen()
.