Course Content
C Tutorial
About Lesson

Binary File Operations

Binary file operations in C offer a powerful way to manipulate files at the binary level. Unlike text files, which store data in a human-readable format, binary files store data in a format that the computer can directly interpret. This makes binary file operations crucial for handling non-textual data like images, videos, and executables.

Opening a Binary File

To work with binary files in C, you start by opening the file using the fopen() function. The file mode used for binary operations is "rb" for reading and "wb" for writing. For instance:

FILE *filePointer;
filePointer = fopen("data.bin", "rb");

Reading from a Binary File

Once the file is open, you can read data using functions like fread() and fgetc(). fread() reads a specified number of bytes from the file, while fgetc() reads a single byte at a time.

// Using fread() to read a block of data
fread(buffer, sizeof(buffer), 1, filePointer);

// Using fgetc() to read byte by byte
char byte;
byte = fgetc(filePointer);

Writing to a Binary File

To write data into a binary file, you use functions like fwrite() and fputc(). fwrite() allows you to write a specified number of bytes into the file, while fputc() writes a single byte at a time.

// Using fwrite() to write a block of data
fwrite(buffer, sizeof(buffer), 1, filePointer);

// Using fputc() to write byte by byte
char byte = 'A';
fputc(byte, filePointer);

Moving within a Binary File

In binary file operations, you can navigate within the file using fseek() to move the file pointer to a specific position. This function allows you to seek a particular byte or offset from the beginning, current position, or end of the file.

// Moving the file pointer to a specific position
fseek(filePointer, offset, SEEK_SET); // SEEK_SET for beginning of file

Closing the Binary File

Always remember to close the file once you’re done with your operations using fclose().