Skip to content

File I/O

In C programming, File I/O (Input/Output) refers to reading from and writing to files stored on secondary storage (like hard disks), rather than working only with console (keyboard/screen).

  • Data persists even after the program ends.
  • Allows handling large data.
  • Used in real-world applications like databases, log systems, and configuration files.

C uses a file pointer (FILE *) to manage files. All file operations are performed through this pointer.

The header file:

#include <stdio.h>

is required for file operations.

Open a file (fopen) -> Perform operations (read/write/append) -> Close the file (fclose) -> File Modes in C

When opening a file using fopen(filename, mode), the mode defines what you can do.

ModeMeaning
"r"Read (file must exist)
"w"Write (create new or overwrite existing)
"a"Append (write at end of file)
"r+"Read + Write (file must exist)
"w+"Read + Write (create new or overwrite)
"a+"Read + Append
  • For binary files, add “b” → e.g., “rb”, “wb”, “ab”.
FILE *fp;
fp = fopen("data.txt", "r"); // open for reading
if(fp == NULL) {
printf("Error opening file!\n");
return 1;
}
  • Always check if file opened successfully.
fclose(fp);
  • Frees resources and ensures data is written properly.
FILE *fp = fopen("data.txt", "w");
fprintf(fp, "Hello, World!\n");
fclose(fp);
fputs("Hello, File Handling!", fp);
fputc('A', fp);
FILE *fp = fopen("data.txt", "r");
char str[50];
fscanf(fp, "%s", str);
  • Problem: Stops at whitespace.
fgets(str, sizeof(str), fp);
char ch = fgetc(fp);
fread(buffer, size, count, fp);
fwrite(buffer, size, count, fp);
  • Used for structures, images, and other non-text data.
FunctionPurpose
ftell(fp)Returns current position in file
fseek(fp, offset, origin)Move file pointer
rewind(fp)Reset pointer to beginning

Example:

fseek(fp, 0, SEEK_END);
long size = ftell(fp);
rewind(fp);
while(!feof(fp)) {
char ch = fgetc(fp);
if(ch != EOF)
putchar(ch);
}
  • Better approach: Check return value of fgetc() instead of feof().
  • Use perror() or strerror(errno) for descriptive errors.
if(fp == NULL) {
perror("File opening failed");
}