File I/O in C Programming - Codingque

Welcome to C Programming Tutorial

Your guide to getting started with C programming.

File I/O in C

File I/O in C involves using functions from the stdio.h library to perform operations such as reading from and writing to files. Here’s a detailed explanation with examples:

File I/O Overview

In C, file I/O operations are performed using file pointers and functions provided by the stdio.h library. The basic operations include opening a file, reading from or writing to the file, and closing the file.

Common File I/O Functions

Example: Writing to a File

#include <stdio.h>

int main() {
    // Open the file for writing ("w" mode). Creates a new file or truncates an existing file.
    FILE *file = fopen("example.txt", "w");
    
    if (file == NULL) {
        // Handle error if file cannot be opened
        perror("Error opening file");
        return 1;
    }

    // Write data to the file
    fprintf(file, "Hello, World!\n");
    fprintf(file, "This is a test file.\n");

    // Close the file
    fclose(file);

    return 0;
}
        

Code Explanation:

#include <stdio.h>:

This line includes the standard input/output library necessary for file operations and other standard I/O functions.

int main():

This is the entry point of the C program. The main function is where the execution of the program begins.

FILE *file = fopen("example.txt", "w");:

FILE *file declares a pointer file of type FILE which is used to handle the file.

fopen("example.txt", "w") opens the file named "example.txt" in "write" mode.

If the file does not exist, it is created.

If the file already exists, it is truncated to zero length (i.e., its contents are deleted).

If the file cannot be opened (e.g., due to permission issues or a full disk), fopen returns NULL.

if (file == NULL):

This conditional statement checks if the file pointer is NULL, which indicates an error in opening the file.

perror("Error opening file");:

If file is NULL, this function prints a descriptive error message to the standard error stream. The message "Error opening file" is prepended to the system-generated error description.

return 1:

The return statement exits the main function and returns a status code of 1, which generally indicates an error or abnormal termination.

fprintf(file, "Hello, World!\n");:

This function writes the string "Hello, World!" followed by a newline character to the file pointed to by file.

fprintf(file, "This is a test file.\n");:

Similarly, this function writes "This is a test file." followed by a newline character to the file.

fclose(file);:

This function closes the file and flushes any buffered output. It is important to close the file to ensure that all data is written to disk and resources are released.

return 0:

The main function returns 0, which indicates successful completion of the program.

Example: Reading from a File

#include <stdio.h>

int main() {
    // Open the file for reading ("r" mode)
    FILE *file = fopen("example.txt", "r");

    if (file == NULL) {
        // Handle error if file cannot be opened
        perror("Error opening file");
        return 1;
    }

    char buffer[100];

    // Read data from the file
    while (fgets(buffer, sizeof(buffer), file) != NULL) {
        // Print the read data to the console
        printf("%s", buffer);
    }

    // Close the file
    fclose(file);

    return 0;
}
        

Code Explanation:

#include <stdio.h>:

This line includes the standard input/output library necessary for file operations and other standard I/O functions.

int main():

This is the entry point of the C program. The main function is where the execution of the program begins.

FILE *file = fopen("example.txt", "r");:

FILE *file declares a pointer file of type FILE which is used to handle the file.

fopen("example.txt", "r") opens the file named "example.txt" in "read" mode.

If the file does not exist or cannot be opened (e.g., due to permission issues), fopen returns NULL.

if (file == NULL):

This conditional statement checks if the file pointer is NULL, which indicates an error in opening the file.

perror("Error opening file");:

If file is NULL, this function prints a descriptive error message to the standard error stream. The message "Error opening file" is prepended to the system-generated error description.

char buffer[100];:

This declares a character array buffer with a size of 100 bytes, used to store lines of text read from the file.

while (fgets(buffer, sizeof(buffer), file) != NULL):

fgets(buffer, sizeof(buffer), file) reads a line from the file into buffer up to sizeof(buffer) - 1 characters or until a newline is encountered.

The while loop continues as long as fgets successfully reads a line (i.e., it does not return NULL).

printf("%s", buffer);:

This prints the content of buffer to the console. Each line read from the file is outputted to the console.

fclose(file);:

This function closes the file and releases any resources associated with it. It’s important to close the file to ensure no resources are leaked and that the file is properly flushed.

return 0:

The main function returns 0, indicating that the program has executed successfully.

Previous Next
Modern Footer