From: Greg C. <gch...@sb...> - 2011-05-11 10:29:22
|
On 2011-05-11 08:31Z, Michael T. wrote: >> >> No need to use fopen, just use O_BINARY in addition to the O_RDONLY >> for binary files. On Windows, the C library makes a difference between >> "binary" and "text" files. >> >> (In fopen(), add a "b" to the mode string.) >> >> --tml > > Why is that? Different operating systems have different line-ending conventions for text files. > I once ported an application to Windows and reading binary files was a problem. > I spent quite a time searching for the cause and than adding the "b" helped. Without "b", those binary files were opened in text mode. > Apparantly, it was working on Linux without it. When a file is read in text mode, the operating system's line delimiters are translated to linefeed characters; when it's written, they're translated back. C and Unix were designed together, so they happen to use the same delimiter--a single linefeed--so text and binary modes work the same way. > Is it not defined by a standard? This is specified by C99 7.19.2/2. > I initially thought the former Linux compiler was just more benevolent. Unix happens to store physical files in C's internal format. If you ignore the difference between text and binary modes, your program will still work correctly on Unix, but it won't be portable. The usual msw convention delimits lines with a carriage-return--line-feed pair, which is how lines were written on a physical teletype. The most benevolent thing the C library can do is translate that delimiter to C's internal representation on input, and the reverse on output. But you don't have to follow that convention for your own files: just adopt a single newline as your own delimiter, and open all files in binary mode, and then your programs and files will work together on any operating system. |