File Structure: Writing and Reading Records Efficiently

Introduction

The most fundamental requirement of any data-oriented application is the ability to create a record. Creating a record is nothing but creating a database structure in which the information is stored on the file. To create a record, we need to write a structure onto the data file. This, in turn, creates what is known as database structure, into which the records are then written and manipulated. Etc.

fwrite()

To create a database structure, i,e. to add a record, c provides the fwrite() function.

Syntax

fwrite(&<name of structure>, <record size>, <number of records to write>, <file pointer>)

where

  • name of the structure is the structure name
  • record size is the size of the structure that is to be written into the file
  • the number of records to write specifies how many records one wants to write at one go..
  • the value is 1.
  • The file pointer is the name of the file pointer associated with the file in which the record has to be written.

Steps to Write a Structure into a File
 

1. Define the Structure

First, you need to define a structure that represents the data you want to store. For example, consider a structure representing an employee.

struct employee {
        int employee_code;
        char employee_name[30];
        char designation[20];
        float salary;
    };

2. Open a File

Open a file where the structure will be written. You need to use the open () function to open the file in a suitable mode. For writing a new file or overwriting an existing one, the mode is "wb" (write binary).

    FILE *file_pointer;
    file_pointer = fopen("employee.dat", "wb");
    if (file_pointer == NULL) {
        fprintf(stderr, "Cannot open file for writing.\n");
        return 1;
    }

3. Prepare the Structure with Data

Populate the structure with the data you want to store. This could be done either manually or by accepting input from the user.

struct employee emp;
    emp.employee_code = 101;
    strcpy(emp.employee_name, "Shikha Tiwari");
    strcpy(emp.designation, "Manager-IT");
    emp.salary = 75000.50;

4. Write the Structure of the File

Use the fwrite() function to write the structure of the file. This function writes the data from the memory to the file exactly as it is, without any conversion.

fwrite(&emp, sizeof(struct employee), 1, file_pointer);

Here’s what the parameters mean.

  1. &emp: The address of the structure in memory.
  2. sizeof(struct employee): The size of the data to be written (in bytes).
  3. 1: The number of records to write (in this case, only one record).
  4. file_pointer: The file to which the data is written.

5. Close the File

After writing the data, always close the file using close () to ensure all data is properly saved and resources are freed.

fclose(file_pointer);

Full example code

Here’s the full example demonstrating the process.

#include <stdio.h>
#include <string.h>
#include <conio.h>
// Define the employee structure
struct employee {
    int employee_code;
    char employee_name[30];
    char designation[20];
    float salary;
};
int main() {
    struct employee emp;  
    FILE *file_pointer;   
    char confirm;         
 
    file_pointer = fopen("employee.dat", "wb");
    if (file_pointer == NULL) {
	fprintf(stderr, "Cannot open employee.dat file for writing.\n");
	return 1;
    }
    printf("Enter the employee code: ");
    scanf("%d", &emp.employee_code);
    fflush(stdin);  
    printf("Enter the employee name: ");
    fgets(emp.employee_name, sizeof(emp.employee_name), stdin);
    emp.employee_name[strcspn(emp.employee_name, "\n")] = 0;  
    printf("Enter the designation: ");
    fgets(emp.designation, sizeof(emp.designation), stdin);
    emp.designation[strcspn(emp.designation, "\n")] = 0;  
    printf("Enter the salary: ");
    scanf("%f", &emp.salary);
    fflush(stdin); 
    printf("Are you sure you want to add this record (Y/N)? ");
    scanf(" %c", &confirm);  
    if (confirm == 'Y' || confirm == 'y') {
	fwrite(&emp, sizeof(struct employee), 1, file_pointer);
	printf("One record written into the file.\n");
    } 
    else
    {
	printf("Record not written.\n");
    }
    fclose(file_pointer);
    return 0;
    getch();
}

Output

Output

Code Explanation

  • Structure Definition: The employee structure contains four fields: employee_code, employee_name, designation, and salary. These fields hold the respective data for an employee.
  • File Opening: The file "employee.dat" is opened in binary write mode ("wb"). This mode ensures that the file is ready to store binary data.
  • Writing Data: The fwrite() function is called with the address of the emp structure. It writes the structure of the file as a single record.
  • File Closing: The file is closed to ensure all data is written and resources are released.

Reading a record from a file into a structure

Reading a record from a file into a structure in C programming is a crucial operation when dealing with stored data. This process involves retrieving data from a file and storing it in a predefined structure so that it can be manipulated or displayed. Below is an explanation of how to accomplish this, along with an example code.

Steps to read a Record from a File into a structure
 

1. Define the Structure

Before reading data from a file, you need a structure that corresponds to the data stored in the file. For example.

struct employee {
        int employee_code;
        char employee_name[30];
        char designation[20];
        float salary;
    };

2. Open the File

Use the fopen() function to open the file in binary read mode ("rb"), which allows you to read data from the file.

    FILE *file_pointer;
    file_pointer = fopen("employee.dat", "rb");
    if (file_pointer == NULL) {
        fprintf(stderr, "Cannot open file for reading.\n");
        return 1;
    }

3. Read the Data

Use the fread() function to read data from the file and put it into the structure. This function reads binary data from the file into the memory where the structure is located.

struct employee emp;
fread(&emp, sizeof(struct employee), 1, file_pointer);

Parameters of fread()

  • &emp: Address of the structure where the data will be stored.
  • sizeof(struct employee): Size of each record in the file (in bytes).
  • 1: Number of records to read.
  • file_pointer: The file from which to read.

4. Close the File

After reading the data, close the file using close () to release the file resource.

fclose(file_pointer);

5. Display or Use the Data

Once the data is read into the structure, you can display or manipulate it as needed.

Full example code

Here is a complete example that reads a record from a file into a structure.

#include <stdio.h>
#include <string.h>
struct employee {
    int employee_code;
    char employee_name[30];
    char designation[20];
    float salary;
};
int main() {
    struct employee emp;  
    FILE *file_pointer;  
    file_pointer = fopen("employee.dat", "rb");
    if (file_pointer == NULL) {
        fprintf(stderr, "Cannot open employee.dat file for reading.\n");
        return 1;
    }
    if (fread(&emp, sizeof(struct employee), 1, file_pointer) == 1) {
        printf("Employee Code: %d\n", emp.employee_code);
        printf("Employee Name: %s\n", emp.employee_name);
        printf("Designation: %s\n", emp.designation);
        printf("Salary: %.2f\n", emp.salary);
    } else {
        printf("Error reading the record from file.\n");
    }
    fclose(file_pointer);
   return 0;
}

Output

Option

Code Explanation

  • Structure Definition: The employee structure is defined with fields for employee code, name, designation, and salary.
  • File Opening: The file "employee.dat" is opened in binary read mode ("rb"). This ensures that the program reads the file in binary format, preserving the exact structure of the data.
  • Reading the Data: The fread() function is used to read one record from the file into the emp structure. If the function successfully reads the data, it returns 1, indicating that one record was read.
  • Error Handling: If fread() fails (for example, if the file is empty or the end of the file is reached), it returns a number less than 1. The program checks this and prints an error message if necessary.
  • Displaying the Data: After successfully reading the data, the program prints the values stored in the emp structure to the console.

Summary

When working with data in C programming, efficiently storing and retrieving structured data is critical. Writing a structure into a file involves using the write () function, which allows the data contained in a structure to be written directly to a binary file, ensuring that all members of the structure are preserved as-is. This operation is crucial for creating records in data-oriented applications, enabling permanent storage and later retrieval. Conversely, reading a record from a file into a structure requires the use of the fread() function. This function reads the binary data from the file and maps it back into the structure, allowing the program to access and manipulate the stored data.

The key to these operations is ensuring that the structure definition in the program matches the data format stored in the file, maintaining data integrity and consistency across file operations. These techniques are foundational in managing data files within C, providing a method for persistent data storage and retrieval using structured data formats.


Similar Articles