C File Operations

C File Operations – Open, Close, Read & Write Files

In C, file operations allow you to perform tasks like opening, reading, writing, and closing files. You use file pointers and various standard functions from <stdio.h>.

๐Ÿ”น fopen() and fclose()

fopen() is used to open a file, and fclose() is used to close it. Always close a file after use.

๐Ÿ“ Example: Open and Close File

#include <stdio.h>

int main() {
    FILE *fp = fopen("demo.txt", "w");
    
    if (fp == NULL) {
        printf("Unable to open file!\n");
        return 1;
    }

    fprintf(fp, "Hello, file operations in C!\n");
    fclose(fp);

    printf("File written and closed successfully.\n");
    return 0;
}

Try It Now

๐Ÿ”น fputc() and fgetc()

fputc() writes a single character to a file, and fgetc() reads a character from a file.

๐Ÿ“ Example: Write and Read Characters

#include <stdio.h>

int main() {
    FILE *fp;

    // Writing to file
    fp = fopen("letters.txt", "w");
    fputc('A', fp);
    fputc('B', fp);
    fclose(fp);

    // Reading from file
    fp = fopen("letters.txt", "r");
    char ch;

    while ((ch = fgetc(fp)) != EOF) {
        printf("Char read: %c\n", ch);
    }

    fclose(fp);
    return 0;
}

Try It Now

๐Ÿ”น feof() – Detecting End of File

The feof() function returns true when the end of a file is reached.

๐Ÿ“ Example: Using feof()

#include <stdio.h>

int main() {
    FILE *fp = fopen("letters.txt", "r");
    char ch;

    if (fp == NULL) {
        printf("File not found!\n");
        return 1;
    }

    while (!feof(fp)) {
        ch = fgetc(fp);
        if (ch != EOF)
            printf("%c ", ch);
    }

    fclose(fp);
    return 0;
}

Try It Now

๐ŸŽฏ Summary of File Functions

  • fopen() โ€“ Opens a file
  • fclose() โ€“ Closes a file
  • fputc() โ€“ Writes a character
  • fgetc() โ€“ Reads a character
  • feof() โ€“ Checks end-of-file

๐Ÿ’ก Practice Challenge

Create a file, write a few characters using fputc(), then reopen it and read using fgetc(). Try adding your name letter-by-letter!