C program to write and read structures to and from a file

C program to write and read structures to and from a file:

In this post, we will learn how to write the content of a structure to a file and how to read its content from that file in C. We can use any read or write any data like integer, string, array etc. to a file. Similarly, we can also write structure data to a file and read structure data from a file in C.

fwrite() and fread():

fwrite() and fread() function can be used to write and read data to and from a file in C. Before using these functions, let’s learn how to use these functions with the definitions for each.

fwrite() definition and return value:

The definition of fwrite() is defined as like below:

size_t fwrite(const void *p, size_t s, size_t n, FILE *st)

Where,

  • p is a pointer to the content that we want to write
  • s is the size of each element to be written to the file. It should be in bytes.
  • n is the total number of elements. Each element is of s bytes size.
  • st is the pointer to a file where we are writing the content.

It returns the total number of elements written to the file. It is an integral value. If the size we are passing to this method i.e. n and the return value is different, it will throw an error.

In this example, we will use fwrite to write the content of a structure to a file.

fread() definition and return value:

fread() is another method we can use to read the contents of a file. The definition of fread() is defined as like below:

size_t fread(void *p, size_t s, size_t n, FILE *f)

Here,

  • p is a pointer to the memory location where we are reading the data.
  • s is the size of each element, it should be in bytes.
  • n is the total number of elements. Each element are s bytes of size.
  • f is the pointer to a file where we are reading the content of the file.

It returns the total number of elements it read. It is an integral value. If this value is different than the total number of elements passed, i.e. n, it can be either the end of the file is reached or an error occurred.

Now, let’s use these two methods to read and write structure data from and to a file in C:

C program algorithm to read and write structure data:

Let’s learn how to read and write structure data in C. We will use fwrite and fread to write and read data to and from a file.

The below algorithm will be used in this program:

  • Create a structure to store the info of employees. This structure will hold the employee id, employee name and employee age.
  • For writing data:
    • Open the file to write the structure info.
    • If no error occurred while opening the file, create a structure variable with some data.
    • Write the variable content to the file.
    • close the file.
  • For reading data:
    • Open the file to read.
    • If no error ocurred while opening the file, read the content of the file to a variable.
    • Print the content.
    • close the file.

C program:

Below is the complete C program:

#include <stdio.h>
#include <stdlib.h>

struct Employee
{
    int id;
    char name[10];
    int age;
};

void writeData(char *fileName, struct Employee emp)
{
    FILE *f = fopen(fileName, "w");
    if (f != NULL)
    {
        int result = fwrite(&emp, sizeof(struct Employee), 1, f);

        if (result == 0)
        {
            printf("Error writing to the given file\n");
            exit(1);
        }
        else
        {
            printf("Structure is written to the file successfully!\n");
        }

        fclose(f);
    }
    else
    {
        printf("Error opening the file to write data\n");
        exit(1);
    }
}

void readData(char *fileName, struct Employee *empData)
{
    FILE *f = fopen(fileName, "r");

    if (f != NULL)
    {
        while (fread(empData, sizeof(struct Employee), 1, f))
            ;
        fclose(f);
    }
    else
    {
        printf("Error opening the file to read data\n");
        exit(1);
    }
}

int main()
{
    char fileName[] = "readme.txt";
    struct Employee emp = {224, "Alex", 30};
    struct Employee empResult;
    writeData(fileName, emp);
    readData(fileName, &empResult);

    printf("Data from file, Id: %d, Age: %d, Name: %s\n", empResult.id, empResult.age, empResult.name);

    return 0;
}

Here,

  • writeData function is used to write structure data to a file and readData function is used to read data from a file to a structure.
    • The writeData function takes the file name and a structure as its parameters and writes the contents of the structure to the file.
    • The readData function takes the file name and the address of an empty structure, reads the structure data from the file given to the structure variable.
  • It first writes the structure emp data to a file and reads the data from the file to the empResult structure.
  • The last line is printing the data after it is loaded from the file to the structure.

Output:

It will give output as like below:

Structure is written to the file successfully!
Data from file, Id: 224, Age: 30, Name: Alex

C read write structure data file

You might also like: