6Unit 6

File I/O, Command-Line & Graphics

8h

Class hours

6

Topics

0%

0/6 done

Progress0/6 topics

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().

ModeMeaningFile exists?File absent?
"r"Read textOpens from startReturns NULL
"w"Write textTruncates to 0 bytesCreates new
"a"Append textWrites at endCreates new
"r+"Read + Write textOpens, no truncateReturns NULL
"rb"Read binaryOpens from startReturns NULL
"wb"Write binaryTruncatesCreates 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.
main.cFile basics — write then read back

Open a file for writing with fprintf, close it, then reopen and read with fgets.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
▶ Output
Press Run ▶ to execute
Ctrl+Enter to run · Tab for indent
Exam Tip

"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 end
fputc(c, fp)Write one character to file
main.cText file I/O — student records with fprintf / fscanf

Write an array of structs to a text file, then read back and display.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
▶ Output
Press Run ▶ to execute
Ctrl+Enter to run · Tab for indent
Exam Tip

"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);
main.cBinary I/O — fwrite, fread, fseek, ftell

Write a struct to a .dat file in binary, then seek to beginning and read it back.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
▶ Output
Press Run ▶ to execute
Ctrl+Enter to run · Tab for indent
Exam Tip

"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.
main.cCommand-line arguments — argc and argv

Print all arguments and greet the first one if provided.

1
2
3
4
5
6
7
8
9
10
11
12
13
▶ Output
Press Run ▶ to execute
Note: In online compilers, argv[0] is the program path and argc = 1 (no extra args). Run locally: ./program YourName
Ctrl+Enter to run · Tab for indent
Exam Tip

"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= 0
BLUE= 1
GREEN= 2
RED= 4
YELLOW= 14
WHITE= 15
main.cBGI Graphics — circle, rectangle, ellipse (Turbo C)

Standard exam pattern: draw shapes with green background and red foreground.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
▶ Output
Press Run ▶ to execute
Note: BGI graphics requires Turbo C. This code shows the standard exam pattern — not executable in online compilers.
Ctrl+Enter to run · Tab for indent
Exam Tip

"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.

1

What are the file opening modes in C? What does each do?

2

What is the difference between fprintf/fscanf and fwrite/fread?

3

What does fseek() do? What are the three SEEK constants?

4

What is EOF and how do you detect it?

5

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 marks

What 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 marks

Write a C program to count the number of words, lines, and characters in a text file.

5 marks

How 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.

if (fp == NULL) { printf("Cannot open file"); exit(1); }
📖

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).

SEEK_SET=start | SEEK_CUR=bookmark | SEEK_END=last page
🗒️

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.

fprintf → students.txt (readable) | fwrite → emp.dat (raw bytes)
💾

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.

fclose(fp); // mandatory — flushes + releases handle

Unit 6 — Before the Exam Checklist

Know the 6 fopen modes (r, w, a, r+, w+, a+) and their text/binary variants
Can write a full file program: fopen → NULL check → fprintf/fscanf loop → fclose
Know fgets vs fscanf: fgets reads a full line; fscanf reads formatted tokens
Know fwrite/fread syntax: (ptr, size, count, fp)
Can use fseek + SEEK_SET to jump to record n in a binary file
Know ftell() returns current byte position as a long int
Know rewind(fp) == fseek(fp, 0, SEEK_SET)
Know feof() returns non-zero when end-of-file is reached
Know the difference: fclose (flushes + closes) vs fflush (flushes, stays open)
Can write a word/line/character counter using fgetc loop
BCAStudyHub

Your complete interactive study guide for TU BCA Semester I — covering all subjects with interactive tools, past papers, and exam prep.

TU BCASemester I

Program Info

University
Tribhuvan University
Program
BCA — Bachelor in Computer Application
Semester
I (First)
Subjects
5 (4 live, 1 coming soon)

Made by SawnN