File Handling using File Pointers

Introduction

C language में file handling का उपयोग data को permanent storage (disk) में store करने के लिए किया जाता है।

जब हम file के साथ काम करते हैं, तो हम सीधे file से interact नहीं करते, बल्कि एक file pointer के माध्यम से करते हैं।

File pointer एक variable होता है जो file को reference करता है।

File Pointer क्या होता है

File pointer एक pointer होता है जो FILE type का होता है।

Syntax:

FILE *fp;

यहाँ:

  • FILE → एक structure है (defined in stdio.h)
  • fp → file pointer variable

File Pointer का Use

File pointer का उपयोग किया जाता है:

  • file open करने के लिए
  • file read/write करने के लिए
  • file close करने के लिए

बिना file pointer के file handling possible नहीं है

Example Program: File Pointer Declaration और Basic Use

#include <stdio.h>
int main() {

FILE *fp;

fp = fopen("test.txt", "w");

if (fp == NULL) {
printf("File not opened\n");
return 1;

}
printf("File opened successfully\n");

fclose(fp);

return 0;
}

Program Explanation

Step-by-step:

1. File Pointer Declaration

FILE *fp;
  • fp एक file pointer है
  • यह file को point करेगा

2. File Open करना

fp = fopen("test.txt", "w");
  • "test.txt" → file name
  • "w" → write mode
  • अगर file नहीं है → create होगी
  • अगर है → overwrite हो जाएगी

3. Error Checking

if (fp == NULL)
  • अगर file open नहीं हुई तो fp = NULL होगा
  • यह good practice है

4. Success Message

printf("File opened successfully\n");

5. File Close करना

fclose(fp);
  • file को properly close करना जरूरी है
  • memory leak avoid होता है

File Opening Modes (Important)

ModeMeaning
"r"Read mode
"w"Write mode
"a"Append mode
"r+"Read + Write
"w+"Read + Write (overwrite)
"a+"Read + Append

Real Life समझ

मान लो file एक notebook है
file pointer उस notebook का page pointer है

  • fopen() → notebook खोलना
  • file pointer → current page
  • fclose() → notebook बंद करना

Important Points

  • File pointer हमेशा FILE * type का होता है
  • stdio.h include करना जरूरी है
  • fopen() के बिना file access नहीं कर सकते
  • fclose() करना जरूरी है

Exam / Practical Tips

  • हमेशा fp == NULL check करो
  • fclose() करना मत भूलना
  • modes (r, w, a) याद रखो

यह topic practical exam में बहुत आता है

Conclusion

File pointer C file handling का सबसे basic और important concept है।
यह file को control करने का माध्यम होता है।

इसके बिना file open, read, write या close करना संभव नहीं है।

Leave a Comment

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

Scroll to Top