Search code examples
cfileembeddedwindows-cefread

problems with fread() always returning 1


I have looked at similar questions, but mine is a bit different. I make sure to open file in binary mode and to check if error occurs while reading.

File contents:

message1, message2, 53467

program to read simple file:

int bytesRead;
FILE* CSV;
CSV = fopen("\\Temp\\csv.txt", "rb");
char dataBuf[128];

while ( (bytesRead = fread(dataBuf, 1, sizeof(dataBuf), CSV) > 0) )
{
        if (ferror(CSV))
            //handle error

        //do stuff with dataBuf contents
}

fread() is always returning 1. ferror is also not entered, so no file reading error. However, the char array dataBuf is filled with the entire message from the file. I am using fread in conjunction with another function so I need to know how many bytes were read using fread(). Any ideas?


Solution

  • Precedence matters.

    Add parenthesis around assignment.

    while  (  (  bytesRead = fread(dataBuf, 1, sizeof(dataBuf), CSV)  )  > 0  )   
              ^                                                       ^
    

    see C_Operator_Precedence_Table

    If you see 1.5.1 File Copying section of The C programming Language By Brian W. Kernighan and Dennis M. Ritchie You will get clear explanation on This.