Click here to Skip to main content
15,892,298 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
To read binary data from a file, I have written a code as follows,

C++
int fd = open(sFilePath, O_RDONLY, 0); //BINARY READ OPERATION
int iBytesToRead = 100;
unsigned char* pBuffer = new unsigned char[iBytesToRead];
while(true)
{
    int iReadBytes = read(fd, pBuffer, iBytesToRead);
    if( !iReadBytes ) break;
}


In Windows (VC9), within 'while' loop, first time it 'read()' returns '63' whatever value (more than 63!) is passed in 'iBytesToRead'. And later on it returns '0' (break from the loop).
But file size is much more than that, as same code for same file works properly in Linux (gcc).

Is there any wrong in this or Am I missing something in it?

Thanks & Regards,
Aniket A. Salunkhe
Posted
Updated 9-Mar-12 2:02am
v2
Comments
#realJSOP 9-Mar-12 8:22am    
Why aren't you using the stream classes?

1 solution

I did not see anything serious wrong. But you should use
C++
int fd = open(sFilePath, O_RDONLY | O_BINARY, 0);

to ensure that the file is opened in binary mode, because the default Windows fmode is O_TEXT.

With binary mode, read should then return iBytesToRead while not just before the end of file.
 
Share this answer
 
Comments
CPallini 9-Mar-12 8:44am    
Good, my 5.
Andy Rama 10-Mar-12 13:04pm    
Thanks a lot. It is working with my sample code.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900