Read/Write Structure From/to A File In C

Read/Write Structure From/to A File In C

When it comes to writing to a file in C, handling strings or integers is straightforward using fprintf and putc. But things can get tricky when dealing with the contents of a struct. That’s where fwrite and fread come in handy. They make it simpler to write and read chunks of data, especially when you’re working with structures. Instead of dealing with individual elements, you can handle the entire block of data more efficiently.

Writing Structure to a File using fwrite

We can use fwrite() function to write a structure in a file. Hence, fwrite() function will write to the file stream in the form of a 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 from which data will be written.
  • size: Size of each element to be written, specified in bytes.
  • nmemb: Number of elements, each of size size, to be written.
  • stream: FILE pointer to the output file stream where the data will be written.

Return Value

Number of objects that will be written

Example

// 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 could read structure from a file using fread() function. This function will read a block of memory from the given stream.

Syntax

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

Parameters

  • ptr: Pointer to the block of memory where the read data will be stored.
  • size: Size of each element to be read, specified in bytes.
  • nmemb: Number of elements, each of size size, to be read.
  • stream: FILE pointer to the input file stream from which data will be read.

Return Value

Number of objects that will be written

Example

// 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

FAQ- Read/Write Structure From/to A File In C

Q1. How to write and read a structure to a file in C?

Ans. fwrite() syntax. is fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream) …
fread() syntax. fread(void *ptr, size_t size, size_t nmemb, FILE *stream) …
Algorithm. Start to Create a Structure Student to declare variables. …
Example Code.
Ouput. will show Contents to file written successfully !

Q2.What is file structure in C?

Ans. The FILE type in C is a structure, defined in stdio.h, representing a file stream. It’s an opaque data type, so users interact with it using pointers, while the library manages its internal details. The FILE structure holds information about the file stream’s state, allowing consistent file I/O operations across different systems.

Q3. How to read from a structure in C?

Ans. The C function to read a structure is fread(). The format is: fread (* struct, size, count, file);

Hridhya Manoj

Hello, I’m Hridhya Manoj. I’m passionate about technology and its ever-evolving landscape. With a deep love for writing and a curious mind, I enjoy translating complex concepts into understandable, engaging content. Let’s explore the world of tech together

Leave a Comment