C Files


In C programming, file handling allows a program to store and retrieve data permanently. While variables in memory exist only during program execution, files provide persistent storage on disk. This makes file handling essential for applications such as databases, logging systems, and data processing programs.

C provides a set of standard functions in the stdio.h library to work with files, enabling reading, writing, and updating data efficiently.

Types of Files in C

Files in C can be categorized as:

  1. Text Files: Store data as human-readable text. Each line ends with a newline character \n.

  2. Binary Files: Store data in binary format, which is more efficient for storage and retrieval but not human-readable.

Choosing between text and binary files depends on the nature of data and required efficiency.

Opening a File

Before reading or writing a file, it must be opened using the fopen() function:

FILE *fopen(const char *filename, const char *mode);
  • filename: Name of the file (can include path).

  • mode: Defines the file operation, such as reading, writing, or appending.

Common file modes:

Mode Description
"r" Read (file must exist)
"w" Write (creates file or overwrites)
"a" Append (writes at end, creates file if needed)
"r+" Read and write (file must exist)
"w+" Write and read (creates or overwrites)
"a+" Append and read (creates if needed)

Example:

#include <stdio.h>

int main() {
    FILE *file = fopen("data.txt", "w");
    if(file == NULL) {
        printf("Error opening file.\n");
        return 1;
    }
    fprintf(file, "Hello, C file handling!\n");
    fclose(file);
    return 0;
}
  • Opens data.txt for writing.

  • fprintf() writes text to the file.

  • fclose() closes the file and frees system resources.

Writing to a File

C provides several functions to write data to a file:

  1. fprintf(FILE *fp, "format", ...) – formatted output to file.

  2. fputs(const char *str, FILE *fp) – writes a string to file.

  3. fputc(int c, FILE *fp) – writes a single character.

Example:

FILE *file = fopen("output.txt", "w");
fprintf(file, "Name: Alice\nAge: 25\n");
fputs("This is a second line.\n", file);
fputc('X', file);
fclose(file);

Reading from a File

C provides multiple ways to read file content:

  1. fscanf(FILE *fp, "format", ...) – reads formatted data.

  2. fgets(char *str, int n, FILE *fp) – reads a line (up to n-1 characters).

  3. fgetc(FILE *fp) – reads a single character.

Example:

FILE *file = fopen("output.txt", "r");
char line[100];

while(fgets(line, sizeof(line), file) != NULL) {
    printf("%s", line);
}
fclose(file);
  • Reads file line by line until end of file (EOF).

  • fgets() prevents buffer overflow by limiting characters read.

Checking for End of File

The feof(FILE *fp) function checks whether the end of a file has been reached.

int c;
FILE *file = fopen("output.txt", "r");

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

if(feof(file))
    printf("\nEnd of file reached.\n");

fclose(file);
  • EOF is a constant indicating the end of file.

  • feof() can be used for conditional checks when reading.

Closing a File

After operations, always close the file using fclose(FILE *fp).

fclose(file);
  • Ensures data is written to disk.

  • Frees system resources associated with the file.

  • Failure to close a file can cause data loss or memory leaks.

Appending Data to a File

To add data without overwriting existing content, use append mode "a":

FILE *file = fopen("output.txt", "a");
fprintf(file, "Appending a new line.\n");
fclose(file);
  • Existing data remains intact.

  • New data is added at the end of the file.

Error Handling in File Operations

Always check if a file is opened successfully:

FILE *file = fopen("nonexistent.txt", "r");
if(file == NULL) {
    perror("File open error");
    return 1;
}
  • fopen() returns NULL if the file cannot be opened.

  • perror() prints a system-generated error message.

Practical Example: File Writing and Reading

#include <stdio.h>

int main() {
    FILE *file = fopen("students.txt", "w");
    if(file == NULL) {
        printf("Unable to create file.\n");
        return 1;
    }

    fprintf(file, "Name: Alice, Age: 20\n");
    fprintf(file, "Name: Bella, Age: 22\n");
    fclose(file);

    // Reading the file
    char line[100];
    file = fopen("students.txt", "r");
    if(file == NULL) return 1;

    printf("File contents:\n");
    while(fgets(line, sizeof(line), file) != NULL) {
        printf("%s", line);
    }

    fclose(file);
    return 0;
}
  • Demonstrates writing multiple lines and reading them back.

  • Uses fprintf() for writing and fgets() for reading.

Summary of the Tutorial

File handling in C is essential for persistent data storage. By using FILE* pointers and functions like fopen(), fclose(), fprintf(), fscanf(), fgets(), and fgetc(), programmers can read, write, and update files efficiently. Proper error checking, closing files, and choosing the right mode ensures data integrity and program stability. Mastery of file handling is crucial for data-driven applications, logs, and real-world programs in C.


Practice Questions

  1. Write a program to create a text file and write your name and age into it.

  2. Create a program to read the content of a text file line by line and display it on the screen.

  3. Write a program to append new data to an existing file without deleting the old content.

  4. Develop a program to count the number of lines in a given text file.

  5. Write a program to copy the contents of one file into another file.

  6. Create a program to read a file character by character and display each character.

  7. Write a program that checks if a file exists and prints an appropriate message.

  8. Develop a program to write integers from 1 to 10 into a file and then read them back.

  9. Write a program to read a file and count the number of words in it.

  10. Create a program to write student details (name, age, grade) into a file and read them back to display in a formatted table.


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

Go Back Top