फाइल को रीडिंग मोड में खोलें। यदि फाइल मौजूद है, तो फाइल में लाइनों की संख्या गिनने के लिए कोड लिखें। यदि फाइल मौजूद नहीं है, तो यह त्रुटि प्रदर्शित करता है कि फाइल नहीं है।
फाइल रिकॉर्ड्स का संग्रह है (या) यह हार्ड डिस्क पर एक स्थान है जहां डेटा स्थायी रूप से संग्रहीत होता है।
फाइलों पर किए जाने वाले ऑपरेशन्स निम्नलिखित हैं:
फाइल का नामकरण
फाइल खोलना
फाइल से पढ़ना
फाइल में लिखना
फाइल बंद करना
सिंटैक्स
फाइल खोलने और नामकरण के लिए सिंटैक्स निम्नलिखित है:
1) FILE *File pointer; Eg: FILE * fptr;
2) File pointer = fopen("File name", "mode");
Eg: fptr = fopen("sample.txt", "r");
FILE *fp;
fp = fopen("sample.txt", "w");
प्रोग्राम 1
#include <stdio.h>
#define FILENAME "Employee Details.txt"
int main(){
FILE *fp;
char ch;
int linesCount = 0;
// फाइल को रीड मोड में खोलें
fp = fopen(FILENAME, "r");
if(fp == NULL){
printf("File \"%s\" does not exist!!!\n", FILENAME);
return -1;
}
// कैरेक्टर दर कैरेक्टर पढ़ें और नई लाइन की जांच करें
while((ch = getc(fp)) != EOF){
if(ch == '\n')
linesCount++;
}
// फाइल बंद करें
fclose(fp);
// लाइनों की संख्या प्रिंट करें
printf("Total number of lines are: %d\n", linesCount);
return 0;
}
आउटपुट
Total number of lines are: 3 Note: employee details.txt file consist of Pinky 20 5000.000000 Here total number of line are 3
प्रोग्राम 2
इस प्रोग्राम में, हम देखेंगे कि फोल्डर में मौजूद न होने वाली फाइल में कुल लाइनों की संख्या कैसे ज्ञात करें।
#include <stdio.h>
#define FILENAME "sample.txt"
int main(){
FILE *fp;
char ch;
int linesCount = 0;
// फाइल को राइट मोड में खोलें
fp = fopen(FILENAME, "w");
printf("enter text press ctrl+z of the end");
while ((ch = getchar()) != EOF){
fputc(ch, fp);
}
fclose(fp);
// फाइल को रीड मोड में खोलें
fp = fopen(FILENAME, "r");
if(fp == NULL){
printf("File \"%s\" does not exist!!!\n", FILENAME);
return -1;
}
// कैरेक्टर दर कैरेक्टर पढ़ें और नई लाइन की जांच करें
while((ch = getc(fp)) != EOF){
if(ch == '\n')
linesCount++;
}
// फाइल बंद करें
fclose(fp);
// लाइनों की संख्या प्रिंट करें
printf("Total number of lines are: %d\n", linesCount);
return 0;
}
आउटपुट
enter text press ctrl+z of the end Hi welcome to Tutorials Point C Pogramming Question & answers ^Z Total number of lines are: 2