Read and write to binary files in C

Reading and writing binary files in C programming allows you to handle non-textual data, such as images, audio, and binary file formats.

Reading Binary Files in C

Reading Binary Data (Using fread)

fread is used to read binary data from a file. It reads a specified number of elements, each of a specified size, into a buffer.

int data[5]; FILE* file = fopen("binaryfile.bin", "rb"); if (file == NULL) { perror("File opening failed"); return 1; } fread(data, sizeof(int), 5, file); // Reads 5 integers into the 'data' array fclose(file);

Writing to Binary Files in C

Writing Binary Data (Using fwrite)

fwrite is used to write binary data to a file. It writes a specified number of elements, each of a specified size, from a buffer to the file.

int data[5] = {1, 2, 3, 4, 5}; FILE* file = fopen("binaryfile.bin", "wb"); if (file == NULL) { perror("File opening failed"); return 1; } fwrite(data, sizeof(int), 5, file); // Writes 5 integers to the file fclose(file);

Custom Binary File Handling

You can manually handle binary data by reading or writing structures directly. This approach is useful when dealing with more complex binary file formats.

struct Record { int id; float value; }; struct Record records[3] = { {1, 3.14}, {2, 2.718}, {3, 1.618} }; FILE* file = fopen("data.bin", "wb"); if (file == NULL) { perror("File opening failed"); return 1; } for (int i = 0; i < 3; i++) { fwrite(&records[i], sizeof(struct Record), 1, file); // Write one record at a time } fclose(file);

Reading and Writing Raw Bytes (Using fread and fwrite)

For more complex binary data, you can use fread and fwrite to handle raw bytes and structures.

FILE* in = fopen("input.dat", "rb"); FILE* out = fopen("output.dat", "wb"); if (in == NULL out == NULL) { perror("File opening failed"); return 1; } unsigned char buffer[1024]; size_t bytes_read; while ((bytes_read = fread(buffer, 1, sizeof(buffer), in)) > 0) { fwrite(buffer, 1, bytes_read, out); } fclose(in); fclose(out);

Which method to use?

The best way to read and write binary files depends on the specific needs of the program. If the program needs to process the data character-by-character, then character-by-character reading and writing should be used. If the program needs to process the data block-by-block, then block-by-block reading and writing should be used.

Conclusion

Reading and writing binary files involves using functions like fread and fwrite to handle non-textual data. fread reads binary data into a buffer, while fwrite writes binary data from a buffer to a file, making it suitable for various applications like handling images, audio, or complex binary file formats. Proper error handling and consideration of data structure are essential for safe binary file operations in C.