Binary file handling in C involves reading from and writing to binary files, which contain data in a binary format. Binary files are typically used to store data that is not text-based, such as images, audio, and video files. The standard C library provides a set of functions for binary file I/O operations. In general, binary file I/O involves the following steps:
1. Open the file: To read from or write to a binary file, it must be opened using the `fopen()` function. The function takes two arguments: the name of the file to be opened and the mode in which the file is to be opened (read, write, or append). If the file cannot be opened, the function returns a `NULL` pointer.
2. Read from the file: To read data from a binary file, you can use the `fread()` function. The `fread()` function reads a specified number of bytes from the file and stores them in a buffer. The function returns the number of bytes that were read.
3. Write to the file: To write data to a binary file, you can use the `fwrite()` function. The `fwrite()` function writes a specified number of bytes to the file, using a buffer as the source of data. The function returns the number of bytes that were written.
4. Close the file: Once you are done reading from or writing to the file, it must be closed using the `fclose()` function. This ensures that any pending data is written to the file and any resources used by the file are released.
Here are some examples of binary file handling in C:
1. Reading from a binary file using `fread()`:
FILE *fp; int data[10]; fp = fopen("myfile.bin", "rb"); fread(data, sizeof(int), 10, fp); fclose(fp);
This code opens a binary file named “myfile.bin” for reading, reads an array of 10 integers from the file, and then closes the file.
2. Writing to a binary file using `fwrite()`:
FILE *fp; int data[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; fp = fopen("myfile.bin", "wb"); fwrite(data, sizeof(int), 10, fp); fclose(fp);
This code opens a binary file named “myfile.bin” for writing, writes an array of 10 integers to the file, and then closes the file.
It’s important to note that binary file handling requires careful attention to byte ordering and data alignment, especially when working with different computer architectures. In addition, you should always check the return values of file I/O functions to ensure that the operations were successful, and to handle any errors appropriately.