Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • C
  • C Basics
  • C Data Types
  • C Operators
  • C Input and Output
  • C Control Flow
  • C Functions
  • C Arrays
  • C Strings
  • C Pointers
  • C Preprocessors
  • C File Handling
  • C Programs
  • C Cheatsheet
  • C Interview Questions
  • C MCQ
  • C++
Open In App
Next Article:
C Program to Print Contents of File
Next article icon

Read/Write Structure From/to a File in C

Last Updated : 10 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

For writing in the file, it is easy to write string or int to file using fprintf and putc, but you might have faced difficulty when writing contents of the struct. fwrite and fread make tasks easier when you want to write and read blocks of data.

Writing Structure to a File using fwrite

We can use fwrite() function to easily write a structure in a file. fwrite() function writes the to the file stream in the form of binary data block.

Syntax of fwrite()

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

Parameters

  • 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.

Return Value

  • Number of objects written.

Example

C
// C program for writing // struct to file #include <stdio.h> #include <stdlib.h>  // a struct to be read and written struct person {     int id;     char fname[20];     char lname[20]; };  int main() {     FILE* outfile;      // open file for writing     outfile = fopen("person.bin", "wb");     if (outfile == NULL) {         fprintf(stderr, "\nError opened file\n");         exit(1);     }      struct person input1 = { 1, "rohan", "sharma" };      // write struct to file     int flag = 0;     flag = fwrite(&input1, sizeof(struct person), 1,                   outfile);     if (flag) {         printf("Contents of the structure written "                "successfully");     }     else         printf("Error Writing to File!");      // close file     fclose(outfile);      return 0; } 

Output
Contents of the structure written successfully

Reading Structure from a File using fread

We can easily read structure from a file using fread() function. This function reads a block of memory from the given stream.

Syntax of fread()

size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream) 

Parameters

  • ptr: pointer to the block of memory to read.
  • size: the size of each element to read(in bytes).
  • nmemb: number of elements.
  • stream: FILE pointer to the input file stream.

Return Value

  • Number of objects written.

Example

C
// C program for reading // struct from a file #include <stdio.h> #include <stdlib.h>  // struct person with 3 fields struct person {     int id;     char fname[20];     char lname[20]; };  // Driver program int main() {     FILE* infile;      // Open person.dat for reading     infile = fopen("person1.dat", "wb+");     if (infile == NULL) {         fprintf(stderr, "\nError opening file\n");         exit(1);     }      struct person write_struct = { 1, "Rohan", "Sharma" };      // writing to file     fwrite(&write_struct, sizeof(write_struct), 1, infile);      struct person read_struct;      // setting pointer to start of the file     rewind(infile);      // reading to read_struct     fread(&read_struct, sizeof(read_struct), 1, infile);      printf("Name: %s %s \nID: %d", read_struct.fname,            read_struct.lname, read_struct.id);      // close file     fclose(infile);      return 0; } 

Output
Name: Rohan Sharma  ID: 1

Related Articles:

  • Structure in C
  • Basics of File Handling in C


Next Article
C Program to Print Contents of File
author
kartik
Improve
Article Tags :
  • C Language
  • C-File Handling

Similar Reads

  • Basics of File Handling in C
    File handling in C is the process in which we create, open, read, write, and close operations on a file. C language provides different functions such as fopen(), fwrite(), fread(), fseek(), fprintf(), etc. to perform input, output, and many different C file operations in our program. Need of File Ha
    13 min read
  • C fopen() Function
    In C, the fopen() function is used to open a file in the specified mode. The function returns a file pointer (FILE *) which is used to perform further operations on the file, such as reading from or writing to it. If the file exists then the fopen() function opens the particular file else a new file
    5 min read
  • EOF, getc() and feof() in C
    In this article, we will discuss the EOF, getc() function and feof() function in C. What is EOF?In C, EOF is a constant macro defined in the <stdlib.h> header file that is used to denote the end of the file in C file handling. It is used by various file reading functions such as fread(), gets(
    3 min read
  • fgets() in C
    In C, fgets() is a built-in function defined in <stdio.h> header file. It reads the given number of characters of a line from the input stream and stores it into the specified string. This function stops reading the characters when it encounters a newline character, has read the given number o
    4 min read
  • fprintf() in C
    fprintf is used to print content in file instead of stdout console. int fprintf(FILE *fptr, const char *str, ...); Example: C/C++ Code // C Program for the above approach #include<stdio.h> int main() { int i, n=2; char str[50]; //open file sample.txt in write mode FILE *fptr = fopen("samp
    1 min read
  • scanf() and fscanf() in C
    In C language, scanf() function is used to read formatted input from stdin. It returns the whole number of characters written in it otherwise, returns a negative value. Syntax: int scanf(const char *characters_set)Time Complexity: O(n) Auxiliary Space: O(n) where n is the length of input. Many of us
    4 min read
  • C fread() Function
    The C fread() is a standard library function used to read the given amount of data from a file stream. Defined inside <stdio.h>, the fread() function reads the given number of elements of specific size from the file stream and stores it in the buffer memory. The total number of bytes read by f
    4 min read
  • fseek() vs rewind() in C
    In C, the functions fseek() and rewind() helps in manipulating the position of the pointer in the opened file but serve different purposes and have distinct working. The below table lists the major differences between fseek() and rewind() in C: Featurefseek()rewind()FunctionalityMoves the file point
    2 min read
  • What is return type of getchar(), fgetc() and getc() ?
    In C, getchar(), fgetc(), and getc() all are the functions used for reading characters from input buffer. This buffer is standard input buffer for getchar() and can be any specified file for getc() and fgetc(). In this article, we will learn about the return type of these functions and why it matter
    3 min read
  • Read/Write Structure From/to a File in C
    For writing in the file, it is easy to write string or int to file using fprintf and putc, but you might have faced difficulty when writing contents of the struct. fwrite and fread make tasks easier when you want to write and read blocks of data. Writing Structure to a File using fwriteWe can use fw
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences