Reputation: 3
I need help in this chunk of code, I'm trying to update my file and my fread returns 0 even though the data im trying to update is found inside the file.
void updateFile(char filename[], int num, int update){
int pos, checker, y;
FILE *fp;
if((fp = fopen("yes.txt", "r+")) != NULL){
pos = 0;
while(checker = fread(&y, sizeof(int), 1, fp) != 0 && y != num){
pos++;
}
if(checker != 0){
fseek(fp, sizeof(int) * pos, SEEK_SET);
fwrite(&update, sizeof(int), 1, fp);
}
fclose(fp);
}
}
data inside the file is {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} Now im trying to find 5(num) inside the file and change it to another number(update). What I know is fread is supposed to return 1 after a successful read of data but in my case, after I found 5 using y != num, fread returns 0 to checker and I don't know why. I expect it was going to be 1 and not 0 and because of that, I can't update my file. Please help.
Upvotes: 0
Views: 263
Reputation: 3776
Without more information on incoming data all I can do is guess at a few things. Also assuming the while loop runs to completion finding nothing. T
int
the binary bytes in the file may be in a different order than you expect. Upvotes: 0
Reputation: 755010
Surely, what you have:
while(checker = fread(&y, sizeof(int), 1, fp) != 0 && y != num){
should be:
while ((checker = fread(&y, sizeof(int), 1, fp)) != 0 && y != num){
As it stands, you're evaluating fread(&y, sizeof(int), 1, fp) != 0 && y != num
and assigning that boolean (0, 1) value to checker
, and then testing whether it was 0 or 1.
Upvotes: 7