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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With