Creating and Processing Files

Introduction

अब तक हमने programs में data को variables और arrays में store किया, लेकिन एक बड़ी limitation थी:

Program बंद होते ही सारा data delete हो जाता है

यानी:

  • data temporary होता है
  • permanent storage नहीं होता

Real-world applications में हमें data को permanently store करना पड़ता है, जैसे:

  • student records
  • employee data
  • reports

इसी समस्या को solve करने के लिए C language में File Handling का concept दिया गया है।

File Handling हमें allow करता है:

  • data को file में save करने के लिए
  • बाद में उसे पढ़ने (read) के लिए
  • modify करने के लिए

File = secondary storage (hard disk) में stored data

Definition

File Handling वह process है जिसके द्वारा हम data को file में store, read और process करते हैं।

Steps in File Handling

  1. File open करना
  2. Data read/write करना
  3. File close करना

File Pointer

File के साथ काम करने के लिए pointer use होता है:

FILE *fp;

File Modes

ModePurpose
“w”write (नई file बनाता है)
“r”read
“a”append (data add करना)

Creating a File

Example 1: File Create और Write करना

#include <stdio.h>

int main()
{
FILE *fp;
fp = fopen("data.txt", "w");
fprintf(fp, "Hello File");
fclose(fp);
return 0;
}

Explanation:

  • "w" mode → नई file create करेगा
  • fprintf() → data लिखेगा
  • fclose() → file बंद करेगा

Example 2: File Read करना

#include <stdio.h>

int main()
{
FILE *fp;
char ch;
fp = fopen("data.txt", "r");

while ((ch = fgetc(fp)) != EOF)
{
printf("%c", ch);
} fclose(fp);
return 0;
}

Output:

Hello File

Explanation:

  • file से character पढ़ा गया
  • EOF तक loop चला

Example 3: Append Data

#include <stdio.h>
int main()
{
FILE *fp;

fp = fopen("data.txt", "a");
fprintf(fp, "\nNew Line");
fclose(fp);
return 0;
}

Explanation:

  • existing file में नया data add हुआ
  • पुराना data delete नहीं हुआ

Example 4: Integer Write और Read

#include <stdio.h>int main()
{
FILE *fp;
int num = 100;

fp = fopen("num.txt", "w");
fprintf(fp, "%d", num);
fclose(fp);

fp = fopen("num.txt", "r");
fscanf(fp, "%d", &num);
printf("%d", num);
fclose(fp);

return 0;
}

Output:

100

Technical Understanding

File handling का use:

  • permanent data storage
  • database-like operations
  • reports generation
  • logs maintain करना

Important Points

  • FILE pointer जरूरी है
  • fopen() से file open होती है
  • fclose() से file बंद होती है
  • mode सही choose करना जरूरी है
  • EOF file end को represent करता है

Exam Points

  • File handling = permanent storage
  • fopen(), fclose() बहुत important हैं
  • modes (r, w, a) पूछे जाते हैं
  • fprintf, fscanf, fgetc important हैं
  • output-based questions आते हैं

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top