Introduction
C language में file handling करते समय data को access करने के दो मुख्य तरीके होते हैं:
- Sequential Access
- Random Access
यह concept बहुत important है क्योंकि यह decide करता है कि data को file से कैसे पढ़ा या लिखा जाएगा।
1. Sequential Access File
Definition
Sequential access में data को शुरुआत से अंत तक क्रम (sequence) में access किया जाता है।
यानी:
- पहले record से शुरू होगा
- फिर next → next → next
बीच का data direct access नहीं कर सकते
Example Program:
#include <stdio.h>
int main() {
FILE *fp;
char ch;
fp = fopen("file.txt", "r");
if (fp == NULL) {
printf("File not found\n");
return 1;
}
while ((ch = fgetc(fp)) != EOF) {
printf("%c", ch);
}
fclose(fp);
return 0;
}
Program Explanation
- file read mode में open की गई
fgetc()से एक-एक character sequentially पढ़ा गया- loop तब तक चला जब तक
EOFनहीं आया
यहाँ data start से end तक ही access हुआ (sequential)
Output Example:
Hello World
Features of Sequential Access
- Data order में access होता है
- Simple और easy
- slow हो सकता है (large files में)
- direct jump possible नहीं
2. Random Access File
Definition
Random access में हम file के किसी भी position से data direct access (jump करके) कर सकते हैं।
यानी:
- start से पढ़ना जरूरी नहीं
- direct किसी भी position पर जा सकते हैं
Important Functions
| Function | Use |
|---|---|
fseek() | pointer को move करना |
ftell() | current position बताना |
rewind() | pointer को start पर लाना |
Example Program:
#include <stdio.h>
int main() {
FILE *fp;
char ch;
fp = fopen("file.txt", "r");
if (fp == NULL) {
printf("File not found\n");
return 1;
}
fseek(fp, 6, SEEK_SET);
ch = fgetc(fp);
printf("Character at position 6: %c\n", ch);
fclose(fp);
return 0;
}
Program Explanation
- file open की गई
fseek(fp, 6, SEEK_SET);- pointer को 6th position पर ले गया
fgetc()से character read किया गया
बिना शुरू से पढ़े direct position access किया गया
Output Example:
Character at position 6: W
(अगर file में “Hello World” है)
Sequential vs Random Access (Difference Table)
| Feature | Sequential Access | Random Access |
|---|---|---|
| Access तरीका | शुरुआत से end तक | कहीं से भी direct |
| Speed | Slow (large files) | Fast |
| Flexibility | कम | ज्यादा |
| Complexity | Simple | थोड़ा complex |
| Use | text reading | database, records |
Real Life Example
Sequential
जैसे book पढ़ना
- page 1 → 2 → 3 → 4
Random
जैसे dictionary use करना
- सीधे किसी भी word पर jump
Advantages
Sequential Access
- easy implementation
- simple logic
Random Access
- fast data retrieval
- specific data access possible
Limitations
Sequential
- direct access नहीं
- time ज्यादा लगता है
Random
- थोड़ा complex
- pointer handling जरूरी
Exam / Practical Tips
fseek(),ftell(),rewind()बहुत important हैं- difference question अक्सर आता है
- example program जरूर याद रखें
Conclusion
Sequential और Random access file handling के दो महत्वपूर्ण तरीके हैं।
- Sequential → simple लेकिन slow
- Random → fast और flexible
Practical programming में random access ज्यादा powerful होता है, खासकर जब large data handle करना हो।