Skip to content

C File I/O

File I/O allows programs to read from and write to files.

1. File Operations

c
#include <stdio.h>

FILE *fp = fopen("file.txt", "r");  // open file
if (fp == NULL) {
    perror("Error opening file");
    return 1;
}

// Read/write operations
fclose(fp);  // close file

2. File Modes

  • "r" - read
  • "w" - write (overwrite)
  • "a" - append
  • "r+" - read and write

3. Reading Files

c
char buffer[100];
while (fgets(buffer, sizeof(buffer), fp) != NULL) {
    printf("%s", buffer);
}

4. Writing Files

c
fprintf(fp, "Hello, World!\n");
fputs("Another line\n", fp);

Content is for learning and research only.