C Read / Write Files

C Read / Write Files – File Handling in C

File handling in C allows you to store data permanently by reading from and writing to files using standard I/O functions. Files are accessed using a pointer of type FILE*.

๐Ÿ”น Writing to a File using fprintf()

This program writes formatted data to a file using fprintf().

๐Ÿ“ Example: Writing Text to File

#include <stdio.h>

int main() {
    FILE *file = fopen("notes.txt", "w");
    if (file == NULL) {
        printf("Error opening file!\n");
        return 1;
    }

    fprintf(file, "Learning C file handling is fun!\n");
    fprintf(file, "Let's write this line to the file.\n");
    fclose(file);

    printf("Data successfully written to notes.txt\n");
    return 0;
}
  

Try It Now

๐Ÿ”น Reading from a File using fgets()

You can read line-by-line from a file using fgets().

๐Ÿ“ Example: Reading Text from File

#include <stdio.h>

int main() {
    char line[100];
    FILE *file = fopen("notes.txt", "r");

    if (file == NULL) {
        printf("Could not open file for reading.\n");
        return 1;
    }

    while (fgets(line, sizeof(line), file)) {
        printf("%s", line);
    }

    fclose(file);
    return 0;
}
  

Try It Now

๐ŸŽฏ Quick Tips

  • Always check if the file pointer is NULL after opening a file.
  • Use fclose() to release the file resource when done.
  • "w" mode overwrites the file; use "a" for appending.

๐Ÿ’ก Challenge

Create a program that accepts user input and writes it to a file, then reads it back and displays it on the screen. You’ll master file I/O in no time! ๐Ÿ’ช