C Programming

⌘K
  1. Home
  2. Docs
  3. C Programming
  4. File Handling in C
  5. Opening and Closing of File

Opening and Closing of File

Learn how to open and close files in C programming using fopen() and fclose(). Understand file pointers, syntax, modes, and examples for file handling in C.


Introduction: Understanding File Handling in C

In C programming, file handling allows programs to store and retrieve data permanently from secondary storage like hard disks.

  • Before performing operations such as reading, writing, or appending, you must first open the file — and once operations are done, you must close it properly to free system resources.

Two important functions are used for these tasks:

  • fopen() — for opening a file
  • fclose() — for closing a file

Let’s understand both in detail.


Opening a File in C

The fopen() function is used to open a file in a specific mode (read, write, or append).
When a file is opened, it returns a file pointer that references the opened file in memory.

Syntax:

FILE *fp;
fp = fopen("filename.txt", "mode");
  • fp → File pointer of type FILE
  • filename.txt → Name of the file to open
  • mode → Operation mode (e.g., "r", "w", "a", "rb", etc.)

Common File Opening Modes

ModeDescription
"r"Opens file for reading (must exist)
"w"Opens file for writing (creates new or overwrites existing)
"a"Opens file for appending new data at the end
"r+"Opens file for reading and writing (file must exist)
"w+"Opens file for reading and writing (overwrites old data)
"a+"Opens file for reading and appending
"rb", "wb", "ab"Open binary files (read/write/append)

Example: Opening a File in Write Mode

#include <stdio.h>

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

    if (fp == NULL) {
        printf("Error: Unable to open file!\n");
        return 1;
    }

    fprintf(fp, "Learning file handling in C.\n");
    fclose(fp);

    printf("Data written successfully!\n");
    return 0;
}

Explanation:

  • fopen() opens the file data.txt in write mode.
  • fprintf() writes formatted data to the file.
  • fclose() closes the file safely.

Closing a File in C

The fclose() function is used to close an opened file.
It ensures that all data in the buffer is written to disk and the file is properly saved.

Syntax:

fclose(file_pointer);

Example:

fclose(fp);

If the file is successfully closed, it returns 0. If there’s an error, it returns EOF (End of File indicator).


Why Closing Files is Important

  • Prevents data loss or corruption
  • Ensures system resources (like memory and file handles) are released
  • Finalizes write operations before program termination
  • Improves program stability and efficiency

Example: Opening, Writing, and Closing a File

#include <stdio.h>

int main() {
    FILE *fp;
    fp = fopen("example.txt", "w");

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

    fprintf(fp, "File opened and closed successfully.\n");

    if (fclose(fp) == 0) {
        printf("File closed properly.\n");
    } else {
        printf("Error closing file!\n");
    }

    return 0;
}

Output:

File closed properly.

Error Handling in File Opening and Closing

Always check if the file pointer is NULL after calling fopen() — it indicates the file could not be opened.
Example:

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

If the file fails to close correctly, check for return value != 0 from fclose().


Difference Between fopen() and fclose()

FunctionPurposeReturn TypeCommon Error
fopen()Opens file in a given modeFile pointer (FILE *)Returns NULL if failed
fclose()Closes opened fileint (0 for success)Returns EOF if failed

Best Practices for File Handling

✅ Always check if file opened successfully before using it.
✅ Close files using fclose() to prevent leaks.
✅ Avoid opening the same file in conflicting modes simultaneously.
✅ Flush buffers before closing if needed (fflush(fp);).
✅ Use meaningful file names and proper extensions.


Conclusion

The opening and closing of file in C are essential operations for safe and effective data handling.
Using fopen() and fclose() correctly ensures that your program can read, write, and manage data efficiently while preventing errors or data corruption.

Mastering these functions forms the foundation for advanced concepts like binary files, file pointers, and data persistence in C programming.

Tags , ,

How can we help?

Leave a Reply

Your email address will not be published. Required fields are marked *