<< Chapter < Page | Chapter >> Page > |
Binary files can be either processed sequentially or, depending on the needs of the application, they can be processed using random access techniques. In C Programming Language, processing a file using random access techniques involves moving the current file position to an appropriate place in the file before reading or writing data. This indicates a second characteristic of binary files – they a generally processed using read and write operations simultaneously.
For example, a database file will be created and processed as a binary file. A record update operation will involve locating the appropriate record, reading the record into memory, modifying it in some way, and finally writing the record back to disk at its appropriate location in the file. These kinds of operations are common to many binary files, but are rarely found in applications that process text files.
For all file operations you should always follow the 5-step plan as outlined below.
In C, we usually create variables of type FILE * to point to a file located on the computer.
FILE *file_pointer_name;
Example
FILE * f1, * f2;
First things first: we have to open a file to be able to do anything else with it. For this, we use fopen function, like all the I/O functions, is made available by the stdio.h library. The fopen() function prototype is as follows.
FILE *fopen(char *filename, char *mode);
In the above prototype, there are two arguments:
Mode | Meaning |
“r” | Open a file for read only, starts at beginning of file (default mode). |
“w” | Write-only, truncates existing file to zero length or create a new file for writing. |
“a” | Write-only, starts at end of file if file exists,otherwise creates a new file for writing. |
“r+” | Open a file for read-write, starts at beginning of file. If the file is not exist, it will cause an error. |
“w+” | Read-write, truncates existing file to zero length or creates a new file for reading and writing. |
“a+” | Read-write, starts at end of file if file exists, otherwise creates a new file for reading and writing. |
So there are 12 different values that could be used: "rt", "wt", "at", "r+t", "w+t", "a+t" and "rb", "wb", "ab", "r+b", "w+b", "a+b".
Character | Type |
“t” | Text File |
“b” | Binary File |
Notification Switch
Would you like to follow the 'Introduction to computer science' conversation and receive update notifications?