tags:

views:

58

answers:

2
fprintf(file, "%d %d %d", array[0], array[1], array[2]);

for this statement to work i have to open the file in 'wb' mode rather than 'w' mode . How does a binary mode make the syntax work?

A: 

First get a file pointer using fopen FILE *fp = fopen("file.bin", "r+"); Then use fread to read and fwrite to .. write. See this Also please do read the manual carefully and note fread and fwrite return an integer which should be checked to see exactly how much has been read/written.

nc3b
A: 

Assuming that you are using this function when "opening" the file:

FILE *fopen(const char *path, const char *mode);

When you are programming under Linux b is ignored, as it doesn't have any effect. From man page:

The mode string can also include the letter 'b' either as a last char‐ acter or as a character between the characters in any of the two-char‐ acter strings described above. This is strictly for compatibility with C89 and has no effect; the 'b' is ignored on all POSIX conforming sys‐ tems, including Linux. (Other systems may treat text files and binary files differently, and adding the 'b' may be a good idea if you do I/O to a binary file and expect that your program may be ported to non-Unix environments.)

As for Windows (source here):

b : Open in binary (untranslated) mode; translations involving carriage-return and linefeed characters are suppressed.

So the conclusion:
If you want portable C code, for compatibility reasons use 'b'.

Andrei Ciobanu
"If you want portable C code, for compatibility reasons use 'b'" is misleading and/or wrong for those writing text files. Your conclusion is only true for binary files or for people who believe that non-CRLF text files are "good enough for most purposes" on Windows and that no other weird-line-endings platforms exist.
John Marshall