কম্পিউটার টিউটোরিয়াল

C-এ ফাইল হ্যান্ডলিং এর মৌলিক অপারেশন (File Handling Basics)


C-এ মৌলিক ফাইল হ্যান্ডলিং অপারেশনগুলো:

  • ফাইলে লেখা (Writing)
  • ফাইল থেকে পড়া (Reading)
  • ফাইলে অ্যাপেন্ড করা (Appending)

১. ফাইলে লেখা

#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.";
    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);
    }
    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.

২. ফাইল থেকে পড়া

পहिले "file_read.txt" ফাইলটি তৈরি করুন নিচের কন্টেন্ট দিয়ে:

You have opened a file using C programming language, in read-only mode.
#include <stdio.h>
int main() {
    FILE *fp;
    char *filename = "file_read.txt";
    char ch;
    fp = fopen(filename, "r");
    if (fp == NULL) {
        printf("%s does not exists \n", filename);
        return 0;
    } 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.

৩. ফাইলে অ্যাপেন্ড করা

পহिले "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 appended later to the file, using C programming.";
    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");
    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 appended later to the file, using C programming.

  1. 7Z ফাইল কী? - 7-Zip কম্প্রেসড ফাইল সম্পর্কে সম্পূর্ণ গাইড

  2. AI ফাইল কী? অ্যাডোব ইলাস্ট্রেটর আর্টওয়ার্ক ফাইল

  3. সি++-এ এক্সেপশন হ্যান্ডেলিং (Exception Handling) বেসিক্স

  4. পাইথন ফাইল হ্যান্ডলিং মাস্টার করুন: ফাইল তৈরি, পড়া, লেখা এবং ডিলিট সহজে