Home Tutorials C Tutorial File Handling
File Handling

File Handling


File Handling in C

What is File Handling?

File Handling is the process of storing data permanently in a file (usually on a hard disk). In C, files are treated as a stream of bytes.

We use file handling when we want our program's output to stay saved even after the computer is turned off. The basic workflow follows these four steps:

  1. Open a file.
  2. Read from or Write to the file.
  3. Close the file to free memory.

Basic Syntax and File Pointer

To work with files, we use a special pointer of type FILE (defined in <stdio.h>).

FILE *fptr;
fptr = fopen("filename.txt", "mode");

// Common Modes:
"w" - Write (creates new or overwrites)
"r" - Read (opens existing)
"a" - Append (adds to the end)

Syntax

FILE *pointer_name;
pointer_name = fopen("file_name", "mode");

Syntax

// Writing
fprintf(file_pointer, "format_string", variables);

// Reading
fscanf(file_pointer, "format_string", &variables);

Syntax

fclose(file_pointer);

Practical Examples

Example 1: Writing to a File

FILE *fptr;
fptr = fopen("test.txt", "w");

if (fptr == NULL) {
    printf("Error opening file!");
} else {
    fprintf(fptr, "Hello SkillEco Students!");
    fclose(fptr); // Always close your files
}

Example 2: Reading from a File

char text[100];
FILE *fptr = fopen("test.txt", "r");

if (fptr != NULL) {
    // Read the first word and print it
    fscanf(fptr, "%s", text);
    printf("Content: %s", text);
    fclose(fptr);
}
Critical Concept: Always check if your file pointer is NULL after using fopen. If the file doesn't exist or you don't have permission to access it, the pointer will be NULL, and trying to use it will crash your program.
Example

🏋️ Test Yourself With Exercises

Take our quiz on File Handling to test your knowledge.

Browse Quizzes »