Translate

Read/Write Structure From/To a File in C – C में Structure को File में पढ़ना और लिखना

क्या आपने कभी सोचा है? आपने C प्रोग्राम में data store किया, लेकिन जैसे ही program बंद हुआ — data गायब! 

यही वह जगह है जहाँ File Handling in C काम आती है। खासकर जब हमें Structure जैसे complex data type को File में save और retrieve करना होता है।

इस लेख में हम step-by-step समझेंगे कि Read/Write Structure From/To a File in C कैसे करते हैं — practical example, code, use-case और best practices के साथ।

📌 Table of Contents

Structure और File Handling क्या है?

Structure C language में एक user-defined data type है जो multiple data types को एक साथ store करता है।

उदाहरण:


struct Student {
    int roll;
    char name[50];
    float marks;
};

अब सोचिए, अगर हमें कई students का record permanently save करना हो तो क्या करेंगे?

यहीं आता है File Handling in C

C में file handling के लिए मुख्य functions:

  • fopen()
  • fclose()
  • fread()
  • fwrite()

जब हम Structure को File में लिखना चाहते हैं, तो सामान्यतः Binary File का उपयोग किया जाता है।

Structure को File में Write कैसे करें?

Step-by-Step Process

  1. Structure define करें
  2. File pointer declare करें
  3. fopen() से file open करें ("wb" mode)
  4. fwrite() से structure data write करें
  5. fclose() से file close करें

Example: Structure Write to File


#include <stdio.h>

struct Student {
    int roll;
    char name[50];
    float marks;
};

int main() {
    FILE *fp;
    struct Student s1 = {1, "Rahul", 85.5};

    fp = fopen("student.dat", "wb");

    fwrite(&s1, sizeof(s1), 1, fp);

    fclose(fp);
    return 0;
}

Explanation:

  • "wb" = write binary mode
  • sizeof(s1) = structure का size
  • fwrite() = structure को file में store करता है

इस तरह हम आसानी से Structure को File में Write कर सकते हैं।

Structure को File से Read कैसे करें?

अब जब data file में store हो गया, तो उसे वापस program में कैसे लाएँ?

Steps:

  1. File को "rb" mode में open करें
  2. fread() से data read करें
  3. Structure variable में store करें
  4. Display करें

Example: Structure Read from File


#include <stdio.h>

struct Student {
    int roll;
    char name[50];
    float marks;
};

int main() {
    FILE *fp;
    struct Student s1;

    fp = fopen("student.dat", "rb");

    fread(&s1, sizeof(s1), 1, fp);

    printf("Roll: %d\n", s1.roll);
    printf("Name: %s\n", s1.name);
    printf("Marks: %.2f\n", s1.marks);

    fclose(fp);
    return 0;
}

यहाँ fread() structure data को binary file से program में लाता है।

Binary File vs Text File

Feature Binary File Text File
Speed Fast Slow
Structure Support Direct Manual Formatting Needed
Functions fread(), fwrite() fprintf(), fscanf()

अगर आप Read/Write Structure From/To a File in C efficiently करना चाहते हैं, तो Binary File बेहतर विकल्प है।

Complete Practical Example (Multiple Records)

मान लीजिए आप 5 students का record save करना चाहते हैं।


struct Student s[5];

fwrite(s, sizeof(s), 1, fp);

और read करने के लिए:


fread(s, sizeof(s), 1, fp);

यह method scalable है और real-world applications जैसे:

  • School Management System
  • Employee Record System
  • Inventory Management

Best Practices & Actionable Tips

✔ Error Handling करें


if(fp == NULL) {
    printf("File not opened!");
}

✔ Always Close the File

Memory leak से बचने के लिए fclose() जरूर करें।

✔ File Mode सही चुनें

  • "wb" → Write Binary
  • "rb" → Read Binary
  • "ab" → Append Binary

✔ Checklist Before Running Program

  • Structure properly define है?
  • File pointer initialized है?
  • Correct mode use किया?
  • Error checking add किया?

Advanced Read/Write Structure From/To a File in C

यह section उन developers के लिए है जो Read/Write Structure From/To a File in C को production-level पर implement करना चाहते हैं। यहाँ हम केवल basic fread() और fwrite() तक सीमित नहीं रहेंगे — बल्कि memory layout, portability, random access, serialization और security जैसे advanced topics cover करेंगे।

Structure Padding & Memory Alignment Deep Dive

जब हम Structure को File में Write करते हैं, तो अक्सर assume करते हैं कि memory layout linear और compact होगा। लेकिन compiler padding जोड़ सकता है।


struct Example {
    char a;
    int b;
};

Expected size = 5 bytes Actual size = 8 bytes (compiler dependent)

⚠ Problem

  • File size mismatch
  • Different compiler → Different structure size
  • Cross-platform read failure

✔ Advanced Fix


#pragma pack(1)
struct Example {
    char a;
    int b;
};
#pragma pack()

Actionable Insight: Production systems में raw memory dump करने की बजाय custom serialization लिखना ज्यादा सुरक्षित होता है।

C Programming thumbnail showing Structure Read Write File Handling with fwrite() and fread() code snippet and .dat file icon

Endianness & Portability Issue

Binary file एक system पर create हुई और दूसरे architecture पर read की गई — data corrupt दिख सकता है।

Concepts:

  • Little Endian
  • Big Endian
  • Network Byte Order

Portable storage के लिए:


#include <arpa/inet.h>

int num = htonl(value);  // host to network

Recommendation: अगर आपका system distributed है, तो Raw Binary File की बजाय structured serialization use करें।

Dynamic Memory Inside Structure (Critical Case)


struct Student {
    int roll;
    char *name;
};

अगर आप इसे सीधे fwrite() करेंगे, तो केवल pointer address save होगा — actual string नहीं।

✔ Correct Approach (Manual Serialization)


int len = strlen(s.name) + 1;
fwrite(&s.roll, sizeof(int), 1, fp);
fwrite(&len, sizeof(int), 1, fp);
fwrite(s.name, sizeof(char), len, fp);

Advanced Insight: इसे कहते हैं Deep Serialization। Production-grade File Handling in C में यह जरूरी है।

Random Access File Handling (Record Update)

Specific record modify करना है? पूरा file rewrite मत करें।


fseek(fp, index * sizeof(struct Student), SEEK_SET);
fwrite(&updatedStudent, sizeof(struct Student), 1, fp);

Use Cases:

  • Employee salary update
  • Inventory stock change
  • Student marks correction

Pro Tip: Record-based binary storage systems इसी technique पर काम करते हैं।

CRUD System Mini Architecture

Create

Append mode ("ab") use करें।

Read

Sequential fread() loop.

Update

fseek() से offset calculate करें।

Delete

Temporary file technique:


while(fread(&s, sizeof(s), 1, fp)) {
    if(s.roll != deleteRoll) {
        fwrite(&s, sizeof(s), 1, temp);
    }
}

Actionable System Design Tip: Production-level student database इसी pattern पर build किया जा सकता है।

Robust Error Handling (Defensive Programming)


if(fp == NULL) {
    perror("File open failed");
    exit(1);
}

if(fwrite(&s, sizeof(s), 1, fp) != 1) {
    perror("Write error");
}

Include:

  • errno
  • Partial write detection
  • Graceful exit strategy

Performance Optimization

✔ Buffered I/O


setvbuf(fp, buffer, _IOFBF, sizeof(buffer));

✔ Large Dataset Handling

  • Chunk-based writing
  • Batch read operations
  • Memory-mapped files (Concept Overview)

High-performance systems में यह critical होता है।

Security Considerations

  • Buffer overflow protection
  • User input validation
  • Binary file tampering check
  • File permission management

Checklist:

  • Input sanitize किया?
  • File existence verify किया?
  • Error logging enabled?

Raw Binary vs Custom Serialization

Feature Raw fwrite() Custom Serialization
Speed High Medium
Portability Low High
Control Low Full

Advanced Recommendation: Production system → Custom serialization.

Enterprise-Level Enhancement Ideas

  • File indexing system
  • Backup & restore logic
  • Corruption recovery mechanism
  • Transaction logging

अगर आप सच में Advanced File Handling in C सीखना चाहते हैं, तो इन concepts को practice में implement करें — सिर्फ पढ़ें नहीं।

1️⃣ fwrite() Function – Syntax, Parameters & Return Value

🔹 Syntax of fwrite()


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

🔹 Parameters Explained

  • ptr → Data का address जिसे file में write करना है
  • size → Single element का size (usually sizeof(struct_name))
  • count → Number of elements to write
  • stream → File pointer

🔹 Return Value

fwrite() successfully written elements की संख्या return करता है।


if(fwrite(&s1, sizeof(s1), 1, fp) != 1) {
    perror("Write failed");
}

Actionable Tip: Production-level File Handling in C में हमेशा return value check करें।

2️⃣ fread() Function – Syntax, Parameters & Return Value

🔹 Syntax of fread()


size_t fread(void *ptr, size_t size, size_t count, FILE *stream);

🔹 Parameters Explained

  • ptr → Memory address जहाँ data store होगा
  • size → Single element size
  • count → Number of elements to read
  • stream → File pointer

🔹 Return Value

fread() successfully read elements की संख्या return करता है।


if(fread(&s1, sizeof(s1), 1, fp) != 1) {
    perror("Read failed");
}

यह validation robust Structure Read from File in C implementation के लिए जरूरी है।

3️⃣ Single Program Example (Write + Rewind + Read)

एक ही program में Structure को write और read दोनों करने का तरीका:


#include <stdio.h>

struct Student {
    int roll;
    char name[50];
};

int main() {
    FILE *fp;
    struct Student s1 = {101, "Amit"};
    struct Student s2;

    fp = fopen("student.dat", "wb+");

    fwrite(&s1, sizeof(s1), 1, fp);

    rewind(fp);  // File pointer reset

    fread(&s2, sizeof(s2), 1, fp);

    printf("Roll: %d\nName: %s\n", s2.roll, s2.name);

    fclose(fp);
    return 0;
}

rewind() file pointer को beginning में ले आता है।

4️⃣ Reading Multiple Records Using Loop Until EOF

Real-world Binary File handling में multiple structures read करने के लिए loop जरूरी है:


while(fread(&s1, sizeof(s1), 1, fp) == 1) {
    printf("Roll: %d\n", s1.roll);
}

यह pattern Persistent Storage in C Programming systems में commonly उपयोग होता है।

5️⃣ Structured Output Formatting

Readable output के लिए formatted printing:


printf("------ Student Record ------\n");
printf("Roll No : %d\n", s1.roll);
printf("Name    : %s\n", s1.name);
printf("----------------------------\n");

यह debugging और production logging दोनों में helpful है।

Frequently Asked Questions (FAQ)

1. C में Structure को File में क्यों लिखते हैं?

Permanent data storage के लिए। Program बंद होने के बाद भी data सुरक्षित रहता है।

2. fread() और fwrite() क्या करते हैं?

Binary file से structure data को read और write करते हैं।

3. क्या Text File में Structure store कर सकते हैं?

हाँ, लेकिन manual formatting की जरूरत होगी। Binary file ज्यादा efficient है।

4. क्या Multiple Structures एक साथ store कर सकते हैं?

हाँ, array of structures को fwrite() से store कर सकते हैं।

5. File open न हो तो क्या करें?

NULL check करें और error message दें।

📌 Further reading

Next
This is the most recent post.
Previous
Older Post

Post a Comment

Blogger

Your Comment Will be Show after Approval , Thanks

Ads

 
↑ Top