File I/O, Command-Line & Graphics
8h
Class hours
6
Topics
0%
0/6 done
Why This Unit Matters
Persist data to files, read and write both text and binary formats, and navigate files with random access. Learn to pass arguments from the command line. Finally, explore Turbo C BGI graphics to draw shapes and text on screen.
File Basics
Files let your program persist data beyond execution. All file operations in C use a FILE* pointer returned by fopen().
| Mode | Meaning | File exists? | File absent? |
|---|---|---|---|
| "r" | Read text | Opens from start | Returns NULL |
| "w" | Write text | Truncates to 0 bytes | Creates new |
| "a" | Append text | Writes at end | Creates new |
| "r+" | Read + Write text | Opens, no truncate | Returns NULL |
| "rb" | Read binary | Opens from start | Returns NULL |
| "wb" | Write binary | Truncates | Creates new |
- —fopen(filename, mode) — returns FILE* on success, NULL on failure. Always check!
- —fclose(fp) — flushes buffers and releases the file handle. Always close after use.
- —fprintf(fp, ...) and fscanf(fp, ...) — like printf/scanf but read/write to a file.
- —fgets(str, n, fp) — reads a full line (safer than fscanf for strings).
- —feof(fp) — returns non-zero when end of file has been reached.
Open a file for writing with fprintf, close it, then reopen and read with fgets.
"What is the difference between text file and binary file? Write a C program to copy contents of student.txt into info.txt." — know: text files store human-readable characters; binary files store raw bytes (more compact, not human-readable).
Text File I/O
Text file functions mirror the console I/O functions you already know. The only difference is the first argument — a FILE pointer instead of stdout/stdin.
fprintf(fp, fmt, ...)Write formatted text to file (like printf)fscanf(fp, fmt, ...)Read formatted text from file (like scanf)fgets(str, n, fp)Read one line (up to n-1 chars + \0)fputs(str, fp)Write a string to file (no newline added)fgetc(fp)Read one character; returns EOF at endfputc(c, fp)Write one character to fileWrite an array of structs to a text file, then read back and display.
"Write a program to store student records (roll, name, marks) in a file and read them back." — use fprintf to write and fscanf to read. The return value check fscanf(...) == 3 is the standard loop condition.
Binary & Random Access I/O
Binary I/O writes raw memory blocks to disk. Combined with fseek, you can jump to any record in a file instantly — enabling random accessrather than sequential reading.
- —fwrite(&var, size, count, fp) — write count items of given size starting at &var.
- —fread(&var, size, count, fp) — read count items of given size into &var.
- —fseek(fp, offset, SEEK_SET) — jump to byte offset from start.
- —fseek(fp, offset, SEEK_CUR) — jump offset bytes from current position.
- —fseek(fp, offset, SEEK_END) — jump offset bytes from end (use 0 to reach end).
- —ftell(fp) — returns current byte position as a long int.
- —rewind(fp) — shorthand for fseek(fp, 0, SEEK_SET); resets to beginning.
- —To access record n: fseek(fp, n * sizeof(struct), SEEK_SET);
Write a struct to a .dat file in binary, then seek to beginning and read it back.
"Explain fseek() and ftell() with example." — know all three SEEK constants. The formula fseek(fp, n * sizeof(record), SEEK_SET) for direct record access is a classic exam question.
Command-Line Arguments
C's main() can receive arguments typed after the program name in the terminal. This is how tools like ./copy input.txt output.txt work.
- —int main(int argc, char *argv[]) — the standard signature for command-line programs.
- —argc (argument count) — total number of arguments including the program name itself.
- —argv (argument vector) — array of C strings; argv[0] is always the program name.
- —argv[1] is the first user argument, argv[2] the second, and so on.
- —argc is always >= 1 (at minimum the program name is present).
- —argv[argc] is always NULL — a sentinel marking the end of the array.
Print all arguments and greet the first one if provided.
"Write a C program to demonstrate command-line argument passing." — clearly show argc and the argv[] loop. Mention that argv[0] is always the program name and argc includes it in the count.
Graphics in C (BGI)
Turbo C uses the BGI (Borland Graphics Interface) library via <graphics.h> to draw shapes and text on screen. This is a standard TU BCA exam topic even though BGI only works in Turbo C (not GCC or online compilers).
initgraph(&gd, &gm, path)Initialize graphics mode. gd = DETECT for auto-detection.setcolor(color)Set foreground (drawing) color. E.g., RED, GREEN, WHITE.setbkcolor(color)Set background color. E.g., GREEN.circle(x, y, r)Draw circle centered at (x,y) with radius r.rectangle(x1,y1,x2,y2)Draw rectangle with top-left (x1,y1) and bottom-right (x2,y2).ellipse(x,y,sa,ea,xr,yr)Draw ellipse at (x,y) with x-radius xr, y-radius yr.line(x1,y1,x2,y2)Draw a straight line between two points.outtextxy(x, y, text)Display a string at pixel position (x,y).closegraph()Close graphics mode and restore text mode.BGI Color Constants
BLACK= 0BLUE= 1GREEN= 2RED= 4YELLOW= 14WHITE= 15Standard exam pattern: draw shapes with green background and red foreground.
"Write a C program to draw a circle, rectangle and ellipse using graphics functions with a green background and red foreground." — exact question from 2024 paper! Memorize: setbkcolor(GREEN), setcolor(RED), then circle/rectangle/ellipse with those coordinates.
Practice & Quiz
Active Recall Questions
Try to answer each question from memory before revealing the answer. This is the most effective study technique for long-term retention.
What are the file opening modes in C? What does each do?
What is the difference between fprintf/fscanf and fwrite/fread?
What does fseek() do? What are the three SEEK constants?
What is EOF and how do you detect it?
What is the difference between fclose() and fflush()?
Exam-Style Questions
These questions match the style and marks distribution of TU BCA past papers. Attempt each question before revealing the full solution.
Write a C program to create a file, write 5 student records (name, roll, marks), then read and display them.
5 marksWhat is random access in a file? Write a C program to update the marks of a specific student (by roll number) in a binary file.
10 marksWrite a C program to count the number of words, lines, and characters in a text file.
5 marksHow to Remember
How to Remember Unit 6
File I/O has many similar-looking functions. These mnemonics and visual anchors lock in the differences and save you from mixing them up under exam pressure.
Mnemonics
Three base file modes
Read Wants Access
R — "r" opens for Reading (file must exist)
W — "w" opens for Writing (creates or wipes)
A — "a" opens for Appending (creates or adds to end)
Add + for read+write access. Add b for binary mode.
fwrite / fread argument order
Sandy Counts Fish
fwrite(&data, Size, Count, File_pointer)
S — Size of one element: sizeof(struct Student)
C — Count of elements to write
F — File pointer (fp)
Same order for fread — just reversed direction.
Memory Tricks
Always check fopen return
fopen returns NULL if the file cannot be opened (wrong path, no permissions, disk full). Always check before using fp — crashing on a NULL FILE pointer is a common beginner bug.
fseek SEEK constants = book metaphor
Think of the file as a book: SEEK_SET = go to the beginning, SEEK_CUR = move from your current bookmark, SEEK_END = go to the last page (then move backwards with negative offset).
fprintf vs fwrite — Notepad test
fprintf writes human-readable text (open the output file in Notepad and you can read it). fwrite writes raw bytes (open in Notepad and you see garbage). Use text for portability; binary for speed and compact size.
fclose is like File > Save
Calling fclose() flushes the internal write buffer to disk and releases the file handle. Without it, your last writes may stay in the buffer and never reach the file — data loss! Always fclose when done.
Unit 6 — Before the Exam Checklist