PadhaikoAll subjects

File Management

Computer Programming (ENCT 101)

Open in the Padhaiko app

9.1 Introduction

Variables, arrays, and structures stored in RAM are volatile: their contents disappear as soon as the program terminates or power is lost. A file is a named collection of related bytes stored persistently on secondary storage (HDD, SSD, USB drive).

In C, file handling through <stdio.h> lets programs store large datasets permanently, share results across separate runs or programs, and process data larger than main memory via buffered streams.


9.2 Binary and text file in C

Every file in C is accessed as either a text stream or a binary stream.

AspectText File (.txt, .csv)Binary File (.bin, .dat)
Data RepresentationStored as human-readable ASCII/UTF-8 character codes (e.g., integer 1234 takes 4 characters '1','2','3','4')Stored in exact raw internal memory bit format (e.g., int 1234 takes fixed 4 bytes sizeof(int))
Newline TranslationOn Windows, '\n' may translate to '\r\n' on write and back to '\n' on readNo character translation; every byte 0x00–0xFF is written and read verbatim
Readability & PortabilityDirectly readable/editable in any text editor; portable across CPUsNot human-readable; faster, more compact for numbers/structs, dependent on byte endianness
Typical I/O Functionsfgetc(), fputc(), fgets(), fputs(), fprintf(), fscanf()fread(), fwrite()

9.3 File opening modes

When opening a file with fopen(filename, mode), the mode string specifies whether the file is opened for reading, writing, or appending, and whether it is text or binary (append b for binary modes: "rb", "wb", "ab", "r+b", "w+b", "a+b").

Standard File Opening Modes in C
ModeMeaningIf File ExistsIf File Does Not Exist
"r"Read text onlyOpens at start for readingFails and returns NULL
"w"Write text onlyTruncates (erases) contents to zero lengthCreates a new empty file
"a"Append text onlyOpens and writes only at the end (preserves existing data)Creates a new empty file
"r+"Read and write (update)Opens at start without erasingFails and returns NULL
"w+"Write and readTruncates existing contents to zeroCreates a new empty file
"a+"Read and appendOpens for reading anywhere; all writes append to endCreates a new empty file

9.4 Defining, opening and closing file

All high-level file I/O in C operates through a file pointer of type FILE * (defined in <stdio.h>), which tracks the OS file descriptor, current buffer position, and EOF/error flags.

Standard Pattern for Defining, Opening, Checking, and Closing a FileC
#include <stdio.h>

int main(void) {
    FILE *fp = fopen("data.txt", "w");
    if (fp == NULL) {
        printf("Error: could not open file.\n");
        return 1;
    }
    fprintf(fp, "Institute of Engineering ENCT 101\n");
    fclose(fp);
    return 0;
}

9.5 Input-output operations on files

9.5.1 Character I/O (fputc(), fgetc())

9.5.2 String I/O (fgets(), fputs())

9.5.3 Formatted I/O (fscanf(), fprintf())

9.5.4 Record I/O (fwrite(), fread())

Used primarily with binary files to read or write entire structures or arrays directly as fixed-size byte blocks:


9.6 Overview of random file access

In sequential access, bytes are read or written from start to finish. Random access jumps directly to any byte offset inside a file using three <stdio.h> positioning functions:

Random File Access Positioning Functions
FunctionSignature / SyntaxPurpose
fseek()int fseek(FILE *fp, long offset, int origin);Moves the file position indicator offset bytes relative to origin: SEEK_SET (0, file start), SEEK_CUR (1, current position), or SEEK_END (2, file end)
ftell()long ftell(FILE *fp);Returns the current byte offset from the start of the file (useful to compute file size after fseek(fp, 0, SEEK_END))
rewind()void rewind(FILE *fp);Resets the file position back to byte 0 (beginning) and clears the error/EOF flags

For example, to jump directly to the 4th record (0-based index 3) of struct Student: fseek(fp, 3L * sizeof(struct Student), SEEK_SET);


9.7 Error handling

File operations can fail due to missing files, permission errors, full disks, or reaching end-of-file unexpectedly. C provides dedicated error-checking helpers in <stdio.h>:

  1. NULL check on fopen(): Always verify fp != NULL immediately after fopen().
  2. int feof(FILE *fp); returns non-zero only after a read attempt hits end-of-file (do not write while (!feof(fp)) before reading, as it executes one extra phantom iteration after the last valid record!).
  3. int ferror(FILE *fp); returns non-zero if a read/write hardware or stream error occurred on fp.
  4. void clearerr(FILE *fp); clears both the EOF and error indicators on fp.
  5. void perror(const char *msg); prints msg: <system error message> to stderr based on the global errno code (<errno.h>).

Worked Examples

Example 1

1 (6 marks)

Write a complete C program that copies the contents of "source.txt" to "dest.txt" character by character using fgetc() and fputc(), handling open errors properly with perror().

Opening Both Streams Safely: Open "source.txt" in "r" mode and "dest.txt" in "w" mode. If either fopen() returns NULL, report the OS reason using perror(), close any already-opened stream, and return non-zero.

Character Copy Loop with int ch: Store fgetc(src) in an int (not char) and loop while ((ch = fgetc(src)) != EOF) so EOF is detected cleanly without misinterpreting valid bytes.

File Copy Program Using fgetc() and fputc()C
#include <stdio.h>

int main(void) {
    FILE *src = fopen("source.txt", "r");
    if (src == NULL) {
        perror("Cannot open source.txt");
        return 1;
    }
    FILE *dst = fopen("dest.txt", "w");
    if (dst == NULL) {
        perror("Cannot open dest.txt");
        fclose(src);
        return 1;
    }

    int ch;
    while ((ch = fgetc(src)) != EOF) {
        fputc(ch, dst);
    }

    if (ferror(src) || ferror(dst)) {
        printf("I/O error during file copy.\n");
    }
    fclose(src);
    fclose(dst);
    return 0;
}
Answer:

Open "source.txt" with "r" and "dest.txt" with "w", check both against NULL, copy with int ch; while ((ch = fgetc(src)) != EOF) fputc(ch, dst);, check ferror(), and close both files with fclose().

Example 2

2 (6 marks)

A binary file "students.dat" stores 4 records of struct Student where sizeof(struct Student) = 40 bytes. Write a C snippet using fwrite(), fseek(), ftell(), and fread() to:

  1. Find the total file size in bytes.
  2. Jump directly to the 3rd student record (1-based: 3rd record, index 2) and read it into struct Student s.

Compute the exact byte offset passed to fseek() and total file size.

Computing File Size with fseek() and ftell(): Seeking to the end with fseek(fp, 0L, SEEK_END); places the indicator at byte 4 * 40 = 160. Calling long sz = ftell(fp); returns 160 bytes.

Random Access to Record 3:

Random Binary Record Access with fseek() and fread()C
FILE *fp = fopen("students.dat", "rb");
if (fp != NULL) {
    fseek(fp, 0L, SEEK_END);
    long total_bytes = ftell(fp);               /* 160 bytes */

    struct Student s;
    fseek(fp, 2L * sizeof(struct Student), SEEK_SET); /* offset = 80 */
    fread(&s, sizeof(struct Student), 1, fp);
    printf("Size=%ld\n", total_bytes);
    fclose(fp);
}
Answer:
  • Total file size returned by ftell(): 160 bytes (4 * 40).
  • Byte offset for the 3rd record (index = 2): 80 bytes (2 * 40), using fseek(fp, 2L * sizeof(struct Student), SEEK_SET);.
Example 3

3 (5 marks)

Write a C program using fprintf() and fscanf() to write 3 student records (roll and marks) into "marks.txt", reopen the file for reading, compute their average marks, and avoid the while (!feof(fp)) pitfall.

Writing with fprintf() and Reading Safely with fscanf(): Instead of while (!feof(fp)), use the return value of fscanf() directly as the loop condition (while (fscanf(fp, "%d %d", &roll, &marks) == 2)), which stops immediately when EOF is reached and never processes a duplicate final line.

Formatted File Write and Read with fprintf() and fscanf()C
#include <stdio.h>

int main(void) {
    FILE *fp = fopen("marks.txt", "w");
    if (fp == NULL) return 1;
    fprintf(fp, "101 85\n102 92\n103 78\n");
    fclose(fp);

    fp = fopen("marks.txt", "r");
    if (fp == NULL) return 1;
    int roll, m, sum = 0, count = 0;
    while (fscanf(fp, "%d %d", &roll, &m) == 2) {
        sum += m;
        count++;
    }
    if (count > 0) {
        printf("Average = %.2f\n", (double)sum / count);
    }
    fclose(fp);
    return 0;
}
Answer:

For {85, 92, 78}, the program computes sum = 255, count = 3, and prints Average = 85.00.


Exercises

Exercises — File Management

Question 1

Differentiate between text files and binary files in C across data storage format, readability, newline handling, and I/O functions used.

Four Comparison Criteria:

  1. Storage Format: Text files encode numbers and strings as human-readable ASCII characters; binary files write raw memory bit patterns directly.
  2. Readability: Text files open cleanly in text editors; binary files appear as non-readable bytes.
  3. Newline Translation: Text mode translates '\n' to platform line endings (e.g., '\r\n' on Windows), whereas binary mode writes every byte verbatim without translation.
  4. I/O Functions: Text files use fgetc, fgets, fprintf, fscanf; binary files use fread and fwrite.
Answer:

Text files store human-readable ASCII characters with platform newline translation using fprintf/fscanf/fgets, whereas binary files store exact raw memory bytes without translation using fread/fwrite.

Question 2

Compare the file opening modes "r", "w", "a", "r+", "w+", and "a+", clearly highlighting what happens when the file already exists versus when it does not exist.

Behavior of the Six Text Modes:

  • "r": Read only; fails (NULL) if missing; preserves existing file.
  • "w": Write only; creates if missing; erases/truncates existing content to 0 bytes.
  • "a": Append only; creates if missing; preserves existing data and writes only at the end.
  • "r+": Read + write; fails (NULL) if missing; preserves existing content and starts at byte 0.
  • "w+": Read + write; creates if missing; truncates existing file to 0 bytes.
  • "a+": Read + append; creates if missing; reads anywhere, writes always at end.
Answer:

"r" and "r+" require the file to exist (return NULL otherwise); "w" and "w+" create missing files and truncate existing ones; "a" and "a+" create missing files and preserve existing contents by writing only at the end.

Question 3

Explain the purpose of fseek(), ftell(), and rewind(). If a binary file "emp.bin" holds 5 employee structures of 64 bytes each, what byte offset does fseek() use to jump to the 5th (last) record from SEEK_SET, and what does ftell() return after fseek(fp, 0L, SEEK_END)?

Random Access Functions:

  • fseek(fp, offset, origin) moves the file pointer relative to SEEK_SET, SEEK_CUR, or SEEK_END.
  • ftell(fp) returns the current byte offset from the start of the file.
  • rewind(fp) resets the pointer to byte 0 and clears EOF/error flags.

Byte Calculations (sizeof(emp) = 64):

  • 5th record (0-based index 4) starts at 4 * 64 = 256 bytes from SEEK_SET.
  • After fseek(fp, 0L, SEEK_END), ftell(fp) returns total file size: 5 * 64 = 320 bytes.
Answer:

fseek() repositions the file cursor, ftell() returns the current byte offset, and rewind() resets to byte 0. Offset to the 5th record = 256 bytes (4 * 64); ftell() at EOF = 320 bytes (5 * 64).

Question 4

Write the function prototypes and roles of fread() and fwrite(). What does fread() return, and how do you verify that a record write or read succeeded?

Signatures and Parameters:

  • size_t fwrite(const void *ptr, size_t size, size_t count, FILE *fp);
  • size_t fread(void *ptr, size_t size, size_t count, FILE *fp);

Here ptr is the memory buffer address, size is bytes per item (sizeof(struct ...)), count is the number of items, and fp is the binary FILE *.

Return Value Verification: Both return the size_t count of complete items successfully transferred. Comparing the return value against count (for instance, if (fread(&rec, sizeof(rec), 1, fp) == 1)) confirms a full record was read; if fewer items return, check feof(fp) vs. ferror(fp).

Answer:

fwrite()/fread() transfer count binary blocks of size bytes between buffer ptr and fp, returning the number of complete records transferred. Success is verified when the returned count equals the requested count.

Question 5

Why is while (!feof(fp)) considered a bug-prone idiom in C file reading loops, and how do ferror() and perror() help handle file I/O errors?

Why while (!feof(fp)) Fails: feof(fp) only becomes true after a read function tries to read past the end of the file and fails. Testing !feof(fp) before reading enters the loop one extra time after the last valid item, causing fscanf/fread to fail while the body processes stale data from the previous iteration. Instead, check the read call itself (while (fscanf(...) == N) or while (fgets(...) != NULL)).

Using ferror() and perror():

  • ferror(fp) distinguishes a true I/O failure from normal EOF after a read loop ends.
  • perror("msg") prints the programmer's prefix followed by the OS error description (errno) to stderr.
Answer:

feof(fp) triggers only after a failed read past EOF, so while (!feof(fp)) causes an extra bogus iteration; check the read function's return value directly instead. Use ferror(fp) to detect hardware/stream failures and perror() to print human-readable OS error messages.

← StructuresRecent Trends in Programming →