File Handling Operations in C

Posted on November 18, 2023 by Vishesh Namdev
Python C C++ Java
C Programming Language

File operations in C involve various functions provided by the stdio.h library. Here's an overview of common file operations:

File Handling Operations in C

Opening a File:

fopen: Opens a file with a specified mode (read, write, append, etc.).

FILE *fptr = fopen("example.txt", "r"); // Open for reading

Writing a File:

fprintf: Writes formatted data to a file.

fprintf(fptr, "This is a line of text\n");

fputc and fputs: a character or string to a file.

fputc('A', fptr); // Write a character

fputs(" Hello, File!", fptr); // Write a string

Reading from a File:

fscanf: Reads formatted data from a file.

fscanf(fptr, "%s", buffer); // Read a string

fgetc and fgets: Reads a character or a line from a file.

char ch = fgetc(fptr); // Read a character fgets(buffer, sizeof(buffer), fptr); // Read a line

Closing a File:

fclose: Closes the file.

fclose(fptr);

Example of File Handling

#include <stdio.h>Copy Code
int main() {
    FILE *filePointer;
    char data[100];

    // Open a file for writing
    filePointer = fopen("example.txt", "w");

    // Check if the file is opened successfully
    if (filePointer == NULL) {
        printf("Error opening the file.\n");
        return 1; // Return an error code
    }

    // Write content to the file
    fprintf(filePointer, "Hello, File Handling in C!");

    // Close the file
    fclose(filePointer);

    // Open the file for reading
    filePointer = fopen("example.txt", "r");

    // Check if the file is opened successfully
    if (filePointer == NULL) {
        printf("Error opening the file for reading.\n");
        return 1; // Return an error code
    }

    // Read and display content from the file
    fscanf(filePointer, "%[^\n]", data);
    printf("Content from the file: %s\n", data);

    // Close the file
    fclose(filePointer);

    return 0; // Return 0 to indicate successful execution
}

This program does the following:

1. Opens a file named "example.txt" for writing.

2. Writes the string "Hello, File Handling in C!" to the file.

3. Closes the file.

4. Opens the same file for reading.

5. Reads the content from the file and displays it on the console.

6. Closes the file.