Introduction
File handling में सबसे पहला और सबसे important step होता है file को open करना
जब तक file open नहीं होगी, तब तक हम उस पर कोई operation (read/write) नहीं कर सकते
इसी तरह, काम पूरा होने के बाद file को close करना भी जरूरी होता है, ताकि:
- data properly save हो जाए
- memory leak न हो
- file corruption न हो
इसलिए हर file operation में ये दो steps जरूरी होते हैं:
- File open करना
- File close करना
अगर हम file close नहीं करेंगे, तो data loss या program error हो सकता है।
Definition
- File Opening → file को access करने के लिए open करना
- File Closing → काम पूरा होने के बाद file को properly बंद करना
Opening a File
Syntax
FILE *fp;fp = fopen("filename", "mode");
Example
FILE *fp;
fp = fopen("data.txt", "w");
Explanation:
data.txt→ file name"w"→ write modefp→ file pointer
File Opening Modes
| Mode | Meaning |
|---|---|
| “r” | Read (file exist होनी चाहिए) |
| “w” | Write (नई file बनाएगा) |
| “a” | Append (existing file में add करेगा) |
Important Concept
fopen() failure check करना जरूरी है
Example 1: File Opening Check
#include <stdio.h>int main()
{
FILE *fp;
fp = fopen("data.txt", "r");
if (fp == NULL)
{
printf("File not found");
}
else
{
printf("File opened successfully");
}
return 0;
}
Output:
File opened successfully
Explanation:
- अगर file नहीं मिले → NULL
- इसलिए checking जरूरी है
Closing a File
Syntax
fclose(fp);
Example 2: Open and Close File
#include <stdio.h>
int main()
{
FILE *fp;
fp = fopen("data.txt", "w");
fprintf(fp, "Hello");
fclose(fp);
return 0;
}
Explanation:
- file open हुई
- data लिखा गया
- file close हुई
Example 3: Read and Close File
#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
Important Rules
- File open किए बिना operation नहीं कर सकते
- File close करना जरूरी है
- fclose() के बाद file use नहीं कर सकते
- Multiple files handle कर सकते हैं
Technical Understanding
- fopen() → file को memory में load करता है
- fclose() → file को save करके release करता है
- NULL check → safe programming
Common Errors
- File open न करना
- fclose() भूल जाना
- wrong mode use करना
- NULL check न करना
Exam Points
- fopen() और fclose() बहुत important हैं
- modes (r, w, a) पूछे जाते हैं
- NULL check जरूरी है
- file closing concept पूछा जाता है
- output-based questions आते हैं