Labs ICT
โญ Pro Login

File Handling

A program that can't talk to files is trapped โ€” it can only work with data typed in each time. File handling lets you save results, read configuration, log errors, and process data that lives beyond a single run.

Opening and Closing Files

fopen opens a file and returns a FILE * pointer. When you're done, fclose closes it. Always check if fopen returned NULL โ€” that means it failed.


#include 
int main() {
  FILE *fp = fopen("hello.txt", "w");
  if (fp == NULL) {
    printf("Could not open file\n");
    return 1;
  }
  fprintf(fp, "Hello, file!\n");
  fclose(fp);
  return 0;
}
    
Try it Yourself โ†’

Reading from Files

fscanf reads formatted data (like scanf but from a file) and fgets reads a whole line. Both are your go-tools for getting data in.


#include 
int main() {
  FILE *fp = fopen("data.txt", "r");
  if (fp == NULL) {
    printf("Could not open file\n");
    return 1;
  }
  char line[256];
  while (fgets(line, sizeof(line), fp)) {
    printf("%s", line);
  }
  fclose(fp);
  return 0;
}
    
Try it Yourself โ†’

File Modes

The mode string tells fopen what you want to do: "r" read, "w" write (creates or overwrites), "a" append (adds to the end). Add "+" for both reading and writing, and "b" for binary mode.


#include 
int main() {
  FILE *fp;
  fp = fopen("log.txt", "a");
  if (fp == NULL) return 1;
  fprintf(fp, "Program started\n");
  fclose(fp);
  fp = fopen("log.txt", "r");
  if (fp == NULL) return 1;
  char ch;
  while ((ch = fgetc(fp)) != EOF) {
    putchar(ch);
  }
  fclose(fp);
  return 0;
}
    
Try it Yourself โ†’

Writing Formatted Output

fprintf works exactly like printf, except it directs output to a file instead of the console. It's your main tool for saving structured data.


#include 
int main() {
  FILE *fp = fopen("students.csv", "w");
  if (fp == NULL) return 1;
  fprintf(fp, "Name,Age,Grade\n");
  fprintf(fp, "Alice,20,92.5\n");
  fprintf(fp, "Bob,22,85.0\n");
  fprintf(fp, "Charlie,19,78.3\n");
  fclose(fp);
  return 0;
}
    
Try it Yourself โ†’

๐Ÿงช Quick Quiz

Which function opens a file in C?