C File I/O Basics

C File I/O Basics – Read and Write Files in C

In C programming, file I/O allows your program to read from and write to files on disk. This is essential for storing data permanently beyond program execution.

๐Ÿ“ฆ File I/O Functions

  • fopen() – Open a file
  • fprintf() / fscanf() – Write/read formatted data
  • fclose() – Close a file
  • fgets() / fputs() – Read/write strings

๐Ÿ“ Example: Write to a File

This example writes text to a file called output.txt.

#include <stdio.h>

int main() {
    FILE *fp = fopen("output.txt", "w"); // Open file for writing
    if (fp == NULL) {
        printf("Error opening file!\n");
        return 1;
    }

    fprintf(fp, "Hello, file I/O in C!\n");
    fclose(fp); // Always close the file

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

Try It Now

๐Ÿ“ Example: Read from a File

This reads and prints content from output.txt.

#include <stdio.h>

int main() {
    char buffer[100];
    FILE *fp = fopen("output.txt", "r"); // Open file for reading
    if (fp == NULL) {
        printf("File not found!\n");
        return 1;
    }

    while (fgets(buffer, sizeof(buffer), fp) != NULL) {
        printf("%s", buffer); // Print each line
    }

    fclose(fp);
    return 0;
}
  

Try It Now

๐Ÿ›  File Modes in fopen()

Mode Description
“r” Open file for reading
“w” Create file for writing (overwrite if exists)
“a” Append to file (create if not exists)
“r+” Read and write
“w+” Read and write (overwrite)
“a+” Read and append

๐ŸŽฏ Practice Tip

Try creating your own file, writing different data types using fprintf, and then reading them back. Remember to always close your files with fclose()! ๐Ÿ—‚๏ธ