এখানে আমরা C-তে কিছু মৌলিক ফাইল হ্যান্ডলিং অপারেশন দেখতে পাব। অপারেশনগুলি নীচে তালিকাভুক্ত করা হয়েছে:
- একটি ফাইলে লেখা
- ফাইল থেকে পড়া
- একটি ফাইলে যুক্ত করা হচ্ছে
একটি ফাইলে লিখুন
আমরা কিভাবে একটি ফাইলে লিখি সেই ধারণা পেতে কোডটি দেখুন
উদাহরণ কোড
#include <stdio.h>
int main() {
FILE *fp;
char *filename = "sample.txt";
char *content = "Hey there! You've successfully created a file with content in c programming language.";
/* open for writing */
fp = fopen(filename, "w");
if( fp == NULL ) {
printf("%s: failed to open. \n", filename);
return -1;
} else {
printf("%s: opened in write mode.\n", filename);
}
/* Write content to file */
fprintf(fp, "%s\n", content);
if( !fclose(fp) )
printf("%s: closed successfully.\n", filename);
return 0;
} আউটপুট
sample.txt: opened in write mode. sample.txt: closed successfully.
2. একটি ফাইল থেকে পড়া
আমরা একটি ফাইল থেকে কীভাবে পড়ি তা ধারণা পেতে কোডটি দেখুন একটি ফাইল তৈরি করুন (file_read.txt):
আপনি C প্রোগ্রামিং ভাষা ব্যবহার করে একটি ফাইল খুলেছেন, শুধুমাত্র-পঠন মোডে।
উদাহরণ কোড
#include <stdio.h>
int main() {
FILE *fp;
char *filename = "file_read.txt";
char ch;
/* open for writing */
fp = fopen(filename, "r");
if (fp == NULL) {
printf("%s does not exists \n", filename);
return;
} else {
printf("%s: opened in read mode.\n\n", filename);
}
while ((ch = fgetc(fp) )!= EOF) {
printf ("%c", ch);
}
if (!fclose(fp))
printf("\n%s: closed.\n", filename);
return 0;
} আউটপুট
file_read.txt: opened in read mode. You have opened a file using C programming language, in read-only mode. file_read.txt: closed.
3.একটি ফাইলে যুক্ত করা হচ্ছে
কিভাবে আমরা একটি ফাইলে লাইন যোগ করতে পারি তা ধারণা পেতে কোডটি দেখুন।
একটি ফাইল তৈরি করুন (file_append.txt)
This text was already there in the file.
উদাহরণ কোড
#include <stdio.h>
int main() {
FILE *fp;
char ch;
char *filename = "file_append.txt";
char *content = "This text is appeneded later to the file, using C programming.";
/* open for writing */
fp = fopen(filename, "r");
printf("\nContents of %s -\n\n", filename);
while ((ch = fgetc(fp) )!= EOF) {
printf ("%c", ch);
}
fclose(fp);
fp = fopen(filename, "a");
/* Write content to file */
fprintf(fp, "%s\n", content);
fclose(fp);
fp = fopen(filename, "r");
printf("\nContents of %s -\n", filename);
while ((ch = fgetc(fp) )!= EOF) {
printf ("%c", ch);
}
fclose(fp);
return 0;
} আউটপুট
Contents of file_append.txt - This text was already there in the file. Appending content to file_append.txt... Content of file_append.txt after 'append' operation is - This text was already there in the file. This text is appeneded later to the file, using C programming.