Last updated : July 27, 2026

FIle Error Handling Tutorials

Programming

Error Handling During File Operations in C

File operations are an important part of C programming. While working with files, various errors can occur such as missing files, insufficient permissions, invalid file pointers, or disk-related issues. Proper error handling helps prevent program crashes and ensures reliable execution.


Why Error Handling is Important?

Without proper error handling:

  • Programs may crash unexpectedly.

  • Incorrect data may be processed.

  • Resources such as files may remain open.

  • Users may receive incorrect output.

Good error handling makes applications more stable and easier to debug.


Common File Operation Errors

Some common errors that occur during file handling are:

File Not Found

Occurs when attempting to open a file that does not exist.

Permission Denied

Occurs when the program does not have sufficient permissions to access a file.

Disk Full

Occurs when there is no available storage space for writing data.

File Already Exists

Occurs when trying to create a file that already exists.

Invalid File Pointer

Occurs when file operations are performed using a NULL file pointer.

End Of File (EOF)

Occurs when reading reaches the end of a file.

File Not Open

Occurs when a file was not opened successfully before performing operations.

File Closing Error

Occurs when fclose() fails to close a file properly.


1. Handling File Not Found Error

When opening a file in read mode, fopen() returns NULL if the file does not exist.

Example

plaintext

#include <stdio.h>

int main()
{
    FILE *file = fopen("file.txt", "r");

    if (file == NULL)
    {
        perror("Error");
        return 1;
    }

    fclose(file);

    return 0;
}

Output

plaintext

Error: No such file or directory

Explanation

  • fopen() tries to open the file.

  • If the file is not found, it returns NULL.

  • perror() displays the system-generated error message.


2. Handling Permission Denied Error

If the program lacks permission to access a file, fopen() fails.

Example

plaintext

#include <stdio.h>

int main()
{
    FILE *file = fopen("/restricted/file.txt", "w");

    if (file == NULL)
    {
        perror("Permission Denied");
    }

    return 0;
}

Output

plaintext

Permission Denied: Permission denied

3. Handling Disk Full Error

Errors during writing can be detected using ferror().

Example

plaintext

#include <stdio.h>

int main()
{
    FILE *file = fopen("data.txt", "w");

    if (file == NULL)
    {
        perror("Error opening file");
        return 1;
    }

    fprintf(file, "Writing data");

    if (ferror(file))
    {
        perror("Error writing file");
    }

    fclose(file);

    return 0;
}

Explanation

  • ferror() checks whether an error occurred during file operations.

  • Useful for detecting write failures such as a full disk.


4. Handling File Already Exists

To prevent overwriting an existing file, use "wx" mode.

Example

plaintext

#include <stdio.h>
#include <errno.h>

int main()
{
    FILE *file = fopen("test.txt", "wx");

    if (file == NULL)
    {
        if (errno == EEXIST)
        {
            printf("File already exists");
        }

        return 0;
    }

    fprintf(file, "New File");

    fclose(file);

    return 0;
}

Output

plaintext

File already exists

5. Handling Invalid File Pointer

Always verify that the file pointer is valid before using it.

Example

plaintext

#include <stdio.h>

int main()
{
    FILE *file = NULL;

    if (file == NULL)
    {
        printf("Invalid file pointer\n");
    }

    return 0;
}

Output

plaintext

Invalid file pointer

6. Handling End Of File (EOF)

Use feof() to determine whether the end of a file has been reached.

Example

plaintext

#include <stdio.h>

int main()
{
    FILE *file = fopen("test.txt", "r");

    char ch;

    while ((ch = fgetc(file)) != EOF)
    {
        putchar(ch);
    }

    if (feof(file))
    {
        printf("\nEnd of file reached");
    }

    fclose(file);

    return 0;
}

Output

plaintext

End of file reached

Explanation

  • fgetc() reads characters one by one.

  • feof() confirms whether EOF was reached.


7. Handling File Not Open Error

Always verify that the file was opened successfully.

Example

plaintext

#include <stdio.h>

int main()
{
    FILE *file = fopen("example.txt", "r");

    if (file == NULL)
    {
        printf("File could not be opened\n");
    }
    else
    {
        printf("File opened successfully\n");
        fclose(file);
    }

    return 0;
}

Output

plaintext

File could not be opened

8. Handling File Closing Error

The fclose() function returns:

  • 0 on success

  • EOF (-1) on failure

Example

plaintext

#include <stdio.h>

int main()
{
    FILE *file = fopen("test.txt", "w");

    fprintf(file, "Hello World");

    if (fclose(file) == EOF)
    {
        printf("File closing error");
    }
    else
    {
        printf("File closed successfully");
    }

    return 0;
}

Output

plaintext

File closed successfully

Useful Error Handling Functions

perror()

Prints a descriptive error message.

plaintext

perror("Error");

ferror()

Checks if an error occurred during file operations.

plaintext

if(ferror(file))
{
    printf("File Error");
}

feof()

Checks if the end of file has been reached.

plaintext

if(feof(file))
{
    printf("EOF Reached");
}

errno

Stores error codes generated by system calls and library functions.

plaintext

#include <errno.h>

Best Practices

  • Always check the return value of fopen().

  • Verify write operations using ferror().

  • Use feof() when reading files.

  • Always close files using fclose().

  • Use perror() for detailed error messages.

  • Check for NULL before using a file pointer.


Summary

  • File operations may fail due to missing files, permissions, invalid pointers, disk issues, or EOF conditions.

  • fopen() should always be checked for NULL.

  • perror() provides system error messages.

  • ferror() detects file operation errors.

  • feof() detects end-of-file conditions.

  • fclose() should always be checked for successful file closure.

  • Proper error handling makes programs reliable, secure, and easier to maintain.

Job PortalJobs