Skip to content

Programming Essentials in C - Lectures 10

File Handling in C

File handling in C refers to performing operations such as creating, opening, reading, writing, appending, renaming, and deleting files using functions provided by the language. These operations allow data to persist beyond the program's execution time by interacting with files stored in the computer's external memory.

Basic File Operations in C

OperationFunction Used
Open a filefopen()
Read from a filefscanf(), fgets(), fread()
Write to a filefprintf(), fputs(), fwrite()
Close a filefclose()

Need for File Handling

When a program uses standard input/output operations, the data is lost once the program ends. File handling ensures data can be stored and reused by saving it externally, thus enabling:

  • Permanent storage of data
  • Data sharing across program runs
  • External memory usage for large data

Types of Files

  1. Text File

    • Stores data as ASCII characters
    • Each line ends with a newline (\n)
    • Common extension: .txt
  2. Binary File

    • Stores data in binary (0s and 1s)
    • Used for non-text data like images, executables
    • Examples: .png, .exe, .jpg

Declaring a File Pointer

c
FILE *filePtr;
  • FILE: A structure defined in stdio.h representing file information.
  • *filePtr: A pointer to this FILE structure.

Opening a File with fopen()

The fopen() function opens or creates a file and returns a pointer to it.

ModeDescription
wWrite mode. Creates file if it doesn't exist.
aAppend mode. Adds data at the end of file.
rRead mode. Opens existing file for reading only.

Syntax

c
FILE *filePtr = fopen("filepath", "mode");

To use an absolute path:

c
FILE *filePtr = fopen("/tmp/test/file.txt", "w");

Closing a File with fclose()

Used to properly close the file and:

  • Save changes
  • Free resources
  • Allow other processes access
c
fclose(filePtr);

Writing to a File

Use w mode to open a file for writing.

  • Overwrites existing content
  • Creates file if it doesn't exist
c
#include <stdio.h>

int main() {
  FILE *filePtr = fopen("data.txt", "w"); // Opening a file in write mode
  int age = 5;

  if (filePtr == NULL) {
    printf("Error opening file.\n");
    return 1;
  }

  // Write to a file
  fprintf(filePtr, "Hello from fprintf!\n");
  fprintf(filePtr, "Hello, my age is %d!\n", age); // using variables
  fputs("Hello from fputs!\n", filePtr);

  fclose(filePtr); // Closing the file
  return 0;
}

Common Functions

FunctionPurposeUse Case
fprintf()Writes formatted textVariables, formatted output
fputs()Writes plain stringSimple line/text
fwrite()Writes binary/raw dataArrays, structs, binary formats

Appending Content to a File

Use a mode to preserve existing data and append new content at the end. If the file does not exist, it will be created.

c
FILE *filePtr = fopen("data.txt", "a");

Reading from a File

Open the file in read mode:

c
FILE *filePtr = fopen("file.txt", "r");

Create a buffer to store read data:

c
char content[255];

Reading a Single Line

c
fgets(content, 255, filePtr);
printf("%s", content);

NOTE

fgets() reads only one line at a time.

fgets could be used to read input from stdin:

c
char name[20];
fgets(name, 20, stdin); // read input from user
printf("My name is: %s", name);

Reading All Lines

Use a loop:

c
while (fgets(content, 255, filePtr)) {
  printf("%s", content);
}

Reading Structured Data: fscanf()

  • Reads formatted values (e.g., string + int)
  • Stops at whitespace or format mismatch
c
fscanf(filePtr, "%s %d", name, &age);

Reading Binary Data: fread()

  • Reads memory blocks
  • Used for structs or binary files
c
fread(buffer, sizeof(type), count, filePtr);

Comparison: fscanf() vs fgets() vs fread()

Featurefscanf()fgets()fread()
Input typeFormatted textFull line (with spaces)Raw/binary data
ReadsWords, numbersOne lineMemory blocks
Structs supportManual parsingUse with sscanf()Direct read
Handles spacesNo (stops at whitespace)YesYes
Best use caseCSV or structured inputReading lines from textBinary files, serialized structs