biggie123
biggie123

Reputation: 3

fread returns 0 even though the data inside is found

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

Answers (2)

Gilbert
Gilbert

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

  • Endianness problems. If the information in your file was not written by a C program writing an int the binary bytes in the file may be in a different order than you expect.
  • Assuming you are reading a binary file with integer values, despite the .txt suffix, you should want to add a "b" option to your open. Else the very low values you are using can be treated as control characters, which can be filtered by libc. In particular the \n and \r can be deleted or generated, depending on the OS you are running on. "b" assures this does not happen. On Linux you should be safe as is.
  • Assuming you are reading a true text file if you are passing in a binary value then things just will not work as true .txt values do not use 50 for '2' rather than \002.

Upvotes: 0

Jonathan Leffler
Jonathan Leffler

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

Related Questions