VOOZH about

URL: https://www.geeksforgeeks.org/c/how-to-write-struct-to-a-binary-file-in-c/

⇱ How to Write a Struct to a Binary File in C? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Write a Struct to a Binary File in C?

Last Updated : 23 Jul, 2025

C file handling allows users to store the data from a C program to a file in either the text or the binary format. In this article, we will learn how to write a struct to a binary file in C.

Writing Structure into a Binary File in C

To write a struct to a binary file, we can use the fwrite() function that writes the given bytes of data in the file in the binary form.

Syntax of fwrite()

size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)

where,

  • ptr: pointer to the block of memory to be written.
  • size: the size of each element to be written (in bytes).
  • nmemb: umber of elements.
  • stream: FILE pointer to the output file stream.

Approach

  1. Open the binary file in write mode
  2. Check if the file is opened successfully. If not print error and exit.
  3. Specify the pointer to the struct, the size of the struct, and the number of instances.
  4. Write the data of the struct to the file using the frwite() method.
  5. Check if the write operation was successful. If not return an error.
  6. Close the file.

C Program to Write a Struct to a Binary File

The following program illustrates how we can write a struct to a binary file in C:


Output
Struct data written to Binary file successfully.

Time Complexity: O(1)
Auxiliary Space: O(1)



Comment