problems with fread() always returning 1

非 Y 不嫁゛ 提交于 2019-12-01 07:07:57

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/19278039/problems-with-fread-always-returning-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!