Writing to Binary Files

At the very beginning of this chapter, the two file types were mentioned: plain text (formally called ASCII) and binary. All of the previous examples have used plain-text files, which are human readable, but you can also write to and read from binary files using C. The basic ideas for working with binary files are the same, but the specific functions are different.

Binary files are opened and closed like ASCII files, except that you should use the b modifier on the mode:

FILE *fp;
fp = fopen ("thefile", "wb");
// Write to the file.

Once you've successfully opened the file, you can write data to it using fwrite(). Its syntax is more complex than you've seen so far:

fwrite (write_data_pointer,
					bytes_to_write, ...

Get C Programming: Visual Quickstart Guide now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.