C Programming Language Tutorial

Variables and Data Types

Input/Output

Looping and Selection Structures

Array

Functions

Preprocessing Command

Pointer

Structure

File Operations

Important Knowledge

​​Read And Write Files in Chunks (fread() And fwrite()) in C Programming Languages

In this tutorial, we'll explore the fread() and fwrite() functions in the C programming language, which are used to read and write binary data to and from a file. We'll cover the basic syntax, usage, and provide some examples to demonstrate their functions.

Basic Syntax

Before using fread() and fwrite(), you should include the stdio.h header at the beginning of your C program.

#include <stdio.h>

The basic syntax for fread() and fwrite() is as follows:

size_t fread(void *ptr, size_t size, size_t count, FILE *stream);
size_t fwrite(const void *ptr, size_t size, size_t count, FILE *stream);
  • fread(): This function reads count elements of data, each size bytes long, from the given stream and stores them in the block of memory pointed to by ptr. The function returns the number of elements actually read, which may be less than count if an error occurs or the end of the file is reached.
  • fwrite(): This function writes count elements of data, each size bytes long, to the given stream from the block of memory pointed to by ptr. The function returns the number of elements actually written, which may be less than count if an error occurs.

Opening and Closing Files

Before using fread() and fwrite(), you need to open the file with fopen() and close it with fclose() when you're done.

The syntax for fopen() and fclose() is:

FILE *fopen(const char *filename, const char *mode);
int fclose(FILE *stream);
  • filename: The name of the file to be opened.
  • mode: The mode in which the file is opened, such as "rb" for reading binary, "wb" for writing binary, and "ab" for appending binary.
  • stream: The file pointer to the open file.

Basic Usage

Let's start with a simple example of reading binary data from a file:

#include <stdio.h>

int main() {
    FILE *file = fopen("input.bin", "rb");
    if (file == NULL) {
        perror("Error opening file");
        return 1;
    }

    int buffer[256];
    size_t bytesRead = fread(buffer, sizeof(int), sizeof(buffer) / sizeof(int), file);

    printf("Read %zu integers\n", bytesRead);

    fclose(file);
    return 0;
}

In this example, we open the file input.bin for reading binary data, read integers using fread(), and then close the file.

Next, let's write binary data to a file:

#include <stdio.h>

int main() {
    FILE *file = fopen("output.bin", "wb");
    if (file == NULL) {
        perror("Error opening file");
        return 1;
    }

    int buffer[] = {1, 2, 3, 4, 5};
    size_t bytesWritten = fwrite(buffer, sizeof(int), sizeof(buffer) / sizeof(int), file);

    printf("Wrote %zu integers\n", bytesWritten);

    fclose(file);
    return 0;
}

In this example, we open the file output.bin for writing binary data, write integers from an array using fwrite(), and then close the file.

  1. Reading files in chunks with fread() in C:

    • Description: fread() is used to read chunks of data from a file. It reads a specified number of elements into a buffer.
    • Code:
      #include <stdio.h>
      
      int main() {
          FILE *file = fopen("binary_input.bin", "rb");
          if (file != NULL) {
              char buffer[1024];
      
              // Read 1024 bytes from the file
              size_t bytesRead = fread(buffer, 1, sizeof(buffer), file);
      
              // Process the read data
              // ...
      
              fclose(file);
          } else {
              printf("Error opening the file.\n");
          }
      
          return 0;
      }
      
  2. Writing files in chunks using fwrite() in C language:

    • Description: fwrite() is used to write chunks of data to a file. It writes a specified number of elements from a buffer.
    • Code:
      #include <stdio.h>
      
      int main() {
          FILE *file = fopen("binary_output.bin", "wb");
          if (file != NULL) {
              char buffer[1024];
      
              // Fill the buffer with data to be written
              // ...
      
              // Write 1024 bytes to the file
              size_t bytesWritten = fwrite(buffer, 1, sizeof(buffer), file);
      
              fclose(file);
          } else {
              printf("Error opening the file.\n");
          }
      
          return 0;
      }
      
  3. Efficient file I/O with fread() and fwrite() functions in C:

    • Description: Combine fread() and fwrite() for efficient reading and writing of files, especially for large datasets.
    • Code:
      #include <stdio.h>
      
      int main() {
          FILE *source = fopen("large_input.bin", "rb");
          FILE *destination = fopen("large_output.bin", "wb");
      
          if (source != NULL && destination != NULL) {
              char buffer[4096];
              size_t bytesRead;
      
              // Read and write in chunks
              while ((bytesRead = fread(buffer, 1, sizeof(buffer), source)) > 0) {
                  fwrite(buffer, 1, bytesRead, destination);
              }
      
              fclose(source);
              fclose(destination);
          } else {
              printf("Error opening files.\n");
          }
      
          return 0;
      }
      
  4. Buffered input and output operations in C programming:

    • Description: Use setbuf() or setvbuf() to set a custom buffer for a file, improving performance for buffered I/O.
    • Code:
      #include <stdio.h>
      
      int main() {
          FILE *file = fopen("buffered_output.txt", "w");
          if (file != NULL) {
              char buffer[BUFSIZ];
      
              // Set a custom buffer for the file
              setbuf(file, buffer);
      
              // Write to the file with the custom buffer
              fputs("Hello, Buffered IO!", file);
      
              fclose(file);
          } else {
              printf("Error opening the file.\n");
          }
      
          return 0;
      }
      
  5. Handling binary data and structured formats with fread() and fwrite():

    • Description: Use fread() and fwrite() for reading and writing binary data, such as structured records in a file.
    • Code:
      #include <stdio.h>
      
      struct Record {
          int id;
          char name[50];
      };
      
      int main() {
          FILE *file = fopen("binary_records.bin", "rb");
          if (file != NULL) {
              struct Record record;
      
              // Read a record from the file
              fread(&record, sizeof(struct Record), 1, file);
      
              // Process the read record
              // ...
      
              fclose(file);
          } else {
              printf("Error opening the file.\n");
          }
      
          return 0;
      }
      
  6. C code examples demonstrating fread() and fwrite() usage:

    • Code:
      #include <stdio.h>
      
      int main() {
          FILE *source = fopen("source.txt", "r");
          FILE *destination = fopen("destination.txt", "w");
      
          if (source != NULL && destination != NULL) {
              char buffer[1024];
              size_t bytesRead;
      
              // Read and write in chunks
              while ((bytesRead = fread(buffer, 1, sizeof(buffer), source)) > 0) {
                  fwrite(buffer, 1, bytesRead, destination);
              }
      
              fclose(source);
              fclose(destination);
          } else {
              printf("Error opening files.\n");
          }
      
          return 0;
      }
      
  7. Random access file operations with fread() and fwrite() in C:

    • Description: Use fseek() to set the file position and then use fread() or fwrite() for random access with chunks of data.
    • Code:
      #include <stdio.h>
      
      int main() {
          FILE *file = fopen("random_access.bin", "r+");
          if (file != NULL) {
              char buffer[1024];
      
              // Set file position to the 5th chunk
              fseek(file, 4 * sizeof(buffer), SEEK_SET);
      
              // Read a chunk from the 5th position
              fread(buffer, 1, sizeof(buffer), file);
      
              // Process the read data
              // ...
      
              // Set file position to the end
              fseek(file, 0, SEEK_END);
      
              // Write a chunk at the end of the file
              fwrite(buffer, 1, sizeof(buffer), file);
      
              fclose(file);
          } else {
              printf("Error opening the file.\n");
          }
      
          return 0;
      }