একটি ফাইল রিডিং মোডে খুলুন। যদি ফাইল থাকে, তবে সেটিতে লাইনের সংখ্যা গণনার কোড লিখুন। ফাইল না থাকলে এরর দেখাবে।
ফাইল হলো রেকর্ডের সংগ্রহ অথবা হার্ড ডিস্কে এমন একটি স্থান যেখানে ডেটা পাবলিকলি স্টোর থাকে।
ফাইলে নিম্নলিখিত অপারেশনগুলো করা হয়—
- ফাইল নামকরণ
- ফাইল খোলা
- ফাইল থেকে পড়া
- ফাইলে লেখা
- ফাইল বন্ধ করা
সিনট্যাক্স
ফাইল খোলা ও নামকরণের সিনট্যাক্স—
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");
প্রোগ্রাম ১
#include <stdio.h>
#define FILENAME "Employee Details.txt"
int main() {
FILE *fp;
char ch;
int linesCount = 0;
// open file in read mode
fp = fopen(FILENAME, "r");
if (fp == NULL) {
printf("File \"%s\" does not exist!!!\n", FILENAME);
return -1;
}
// read character by character and check for new line
while ((ch = getc(fp)) != EOF) {
if (ch == '\n')
linesCount++;
}
// close the file
fclose(fp);
// print number of lines
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
প্রোগ্রাম ২
এই প্রোগ্রামে ফোল্ডারে না থাকা ফাইলের লাইন সংখ্যা বের করা দেখানো হলো।
#include <stdio.h>
#define FILENAME "sample.txt"
int main() {
FILE *fp;
char ch;
int linesCount = 0;
// open file in write mode
fp = fopen(FILENAME, "w");
printf("enter text press ctrl+z of the end");
while ((ch = getchar()) != EOF) {
fputc(ch, fp);
}
fclose(fp);
// open file in read mode
fp = fopen(FILENAME, "r");
if (fp == NULL) {
printf("File \"%s\" does not exist!!!\n", FILENAME);
return -1;
}
// read character by character and check for new line
while ((ch = getc(fp)) != EOF) {
if (ch == '\n')
linesCount++;
}
// close the file
fclose(fp);
// print number of lines
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