Wednesday, April 11, 2007

Mingw/Dev-C++ binary file operations

I encountered this problem when I was porting a Linux utility program to Windows. The job of the utility is to read a XML file and generate a equivalent binary file. I have written it in Linux few weeks before and it works without any issue. When I ported and run the program everything went fine except the reading part of the utility. The utility suppose to read the generated binary file for verification but it fails. The problem is 'read' function returns '0'(indication of EOF) though it has data to read. I have gone through the code many times and found nothing wrong. Then I goggled and found that any file opening in Windows will be in text mode if unspecified.

This can be solved if I use 'fopen' call("rb" mode) but I use 'open' system call. So I again googled and found that I can include the binmode.o(in Mingw lib directory) object along with my executable and which forces the binary mode file open as default. This can also be done by

#include ...
#undef _fmode
int _fmode = _O_BINARY;


No comments: