Programming In CUnit 311 min read
Input/Output Functions & Formatted I/O in C: scanf/printf, File Modes, Debugging
Unit 3 of Programming In C covers formatted I/O functions (scanf, printf), file handling modes (r, w, a, +), and debugging techniques with practical examples, traces, and real-world applications like transaction logs in eSewa or order processing in Daraz.
TAKEAWAYS:
printf/scanfformat specifiers (%d,%f,%c) control input/output precision and type.- File modes (
r,w,a,r+) determine read/write/append behavior and file pointer positioning. - Debugging uses
fprintf(stderr, ...)for error messages andfflush(stdout)to force output. - Common pitfalls: Uninitialized variables, buffer overflows, and mismatched format specifiers.
- Real-world tie: Daraz’s order queue uses
fprintfto log transactions; eSewa’s payment records usefopenin append mode. - Exam focus: Write programs with formatted I/O, explain file modes, and trace variable states step-by-step.
Core Concepts: Formatted I/O Functions
1. printf and scanf Basics
The formatted I/O functions in C allow precise control over input/output operations using format specifiers. These functions are declared in the <stdio.h> header.
Format Specifiers Table
| Specifier | Meaning | Example |
|---|---|---|
%d |
Decimal integer | printf("%d", 10) |
%f |
Floating-point | printf("%f", 3.14) |
%c |
Single character | printf("%c", 'A') |
%s |
String (null-terminated) | printf("%s", "Hello") |
%p |
Pointer address | printf("%p", &var) |
%.2f |
Floating-point with 2 decimals | printf("%.2f", 3.14159) |
Example: Reading and Printing Student Data
#include <stdio.h>
int main() {
int rollno;
char name[50];
float cgpa;
printf("Enter rollno, name, and CGPA: ");
scanf("%d %s %f", &rollno, name, &cgpa);
printf("Student: %d, %s, %.2f\n", rollno, name, cgpa);
return 0;
}
Trace Table for Input/Output
| Step | rollno |
name |
cgpa |
Output Displayed |
|---|---|---|---|---|
| 1 | - | - | - | Enter rollno, name, and CGPA: |
| 2 | 101 | "Rohan" | 3.75 | Student: 101, Rohan, 3.75 |
Visual: Buffer Handling in scanf
flowchart TD
A["User Input: 101 Rohan 3.75"] --> B["scanf Buffer"]
B --> C["%d: Extracts 101 into rollno"]
B --> D["%s: Extracts 'Rohan' into name"]
B --> E["%f: Extracts 3.75 into cgpa"]
C --> F["rollno = 101"]
D --> G["name = 'Rohan\\0'"]
E --> H["cgpa = 3.75"]2. File Handling Modes
Files in C are opened using fopen(), which takes two arguments: filename and mode. The mode determines how the file is accessed.
File Modes Table
| Mode | Description | Example Use Case |
|---|---|---|
r |
Open for reading (file must exist) | Reading a log file (eSewa_transactions.log) |
w |
Open for writing (creates new file or truncates existing) | Writing a new report (sales_report.txt) |
a |
Open for appending (writes at end of file) | Logging orders (Daraz_orders.log) |
r+ |
Open for reading and writing (file must exist) | Updating a database (student_records.dat) |
w+ |
Open for reading and writing (creates new file or truncates existing) | Temporary scratch files |
a+ |
Open for reading and appending (creates new file if needed) | Audit trails |
Example: Appending to a File (eSewa Transaction Log)
#include <stdio.h>
int main() {
FILE *fp = fopen("eSewa_transactions.log", "a");
if (fp == NULL) {
printf("Error opening file!\n");
return 1;
}
fprintf(fp, "Transaction: User123, Amount: 500, Time: %s\n", __TIME__);
fclose(fp);
return 0;
}
State After Each Step
sequenceDiagram
participant User as User
participant Program as Program
participant File as eSewa_transactions.log
User->>Program: Opens file in "a" mode
Program->>File: Checks if file exists (yes)
Program->>File: Moves pointer to end of file
Program->>File: Writes "Transaction: User123, Amount: 500, Time: 14:30:00"
Program->>File: Closes fileVisual: File Pointer Movement in a Mode
3. Debugging and Error Handling
Debugging involves identifying and fixing errors in code. Common techniques include:
- Using
fprintf(stderr, ...)for error messages. - Checking return values of functions (e.g.,
fopenreturnsNULLon failure). - Using
fflush(stdout)to force output when buffering causes delays.
Example: Debugging a File Operation
#include <stdio.h>
int main() {
FILE *fp = fopen("nonexistent.txt", "r");
if (fp == NULL) {
fprintf(stderr, "Error: Could not open file!\n");
return 1;
}
fflush(stdout); // Ensure error message is displayed immediately
fclose(fp);
return 0;
}
Trace Table for Debugging Steps
| Step | Action | Output/State |
|---|---|---|
| 1 | fopen("nonexistent.txt", "r") |
fp = NULL (file not found) |
| 2 | fp == NULL check |
true |
| 3 | fprintf(stderr, ...) |
Error printed to stderr |
| 4 | fflush(stdout) |
Forces any buffered output |
In the Real World
eSewa Transaction Logs
- Idea Used: File handling in append mode (
"a"). - How: Every transaction (e.g.,
User123paying500) is logged toeSewa_transactions.logwithout overwriting previous records. This ensures an audit trail for disputes. - Code Snippet:
FILE *log = fopen("eSewa_transactions.log", "a"); fprintf(log, "%s,%d,%.2f\n", userID, amount, timestamp); fclose(log);
- Idea Used: File handling in append mode (
Daraz Order Processing
- Idea Used: Formatted I/O (
printf/scanf) and file modes ("w"for new orders,"a"for updates). - How: Orders are read from
orders.txt(mode"r"), processed, and written toprocessed_orders.txt(mode"a"). The system usesscanfto parse order details likeorderID,product, andquantity. - Trace Example:
- Input file (
orders.txt):1001,Book,5 1002,Laptop,1 - After processing,
processed_orders.txtappends:Order 1001: Book (5) - Shipped Order 1002: Laptop (1) - Processing
- Input file (
- Idea Used: Formatted I/O (
Ncell Billing System
- Idea Used: File modes (
"r+"for updating customer records). - How: Customer data (e.g.,
customerID,balance) is stored incustomers.dat. When a user top-ups, the system opens the file in"r+"mode, updates the balance, and writes back to the same file. - Visual: File Update Process
flowchart LR A["Open customers.dat in r+"] --> B["Read customerID 123"] B --> C["Update balance: 500 + 100 = 600"] C --> D["Write updated record back to file"] D --> E["Close file"]
- Idea Used: File modes (
Worked Example: Bank Loan Interest Calculator
Problem: Write a program to calculate the monthly interest for a loan using formatted I/O. The user inputs principal, rate, and time (in years), and the program outputs the monthly interest.
Solution Code
#include <stdio.h>
int main() {
float principal, rate, time;
printf("Enter principal, rate (%%), and time (years): ");
scanf("%f %f %f", &principal, &rate, &time);
float monthly_rate = (rate / 100) / 12;
float monthly_interest = principal * monthly_rate;
printf("Monthly Interest: %.2f\n", monthly_interest);
return 0;
}
Trace Table for Input/Output
| Step | principal |
rate |
time |
monthly_rate |
monthly_interest |
Output Displayed |
|---|---|---|---|---|---|---|
| 1 | - | - | - | - | - | Enter principal, rate (%%), and time (years): |
| 2 | 100000 | 5.0 | 5.0 | 0.0041667 | 416.67 | Monthly Interest: 416.67 |
Visual: Interest Calculation Flow
flowchart TD
A["Start"] --> B["Input principal, rate, time"]
B --> C["Calculate monthly_rate = (rate/100)/12"]
C --> D["Calculate monthly_interest = principal * monthly_rate"]
D --> E["Print monthly_interest"]
E --> F["End"]Common Pitfalls and Best Practices
Mismatched Format Specifiers
- Error:
scanf("%d", &float_var)causes undefined behavior. - Fix: Use
%ffor floating-point variables. - Example:
float salary; scanf("%f", &salary); // Correct
- Error:
Buffer Overflow in
scanf- Error:
scanf("%s", name)withnamedeclared aschar name[5]can overflow if input is longer than 4 characters. - Fix: Use
scanf("%4s", name)to limit input size or usefgets. - Example:
char name[50]; scanf("%49s", name); // Leaves space for null terminator
- Error:
Forgetting to Close Files
- Error: Leaks file descriptors and may corrupt data.
- Fix: Always use
fcloseafter operations. - Example:
FILE *fp = fopen("data.txt", "r"); // ... operations ... fclose(fp); // Critical!
Exam Tip
For Short Notes (2x5 Marks)
- File Modes: Define each mode (
r,w,a,r+) with a one-sentence use case (e.g.,"a"for logging). - Debugging: Mention
fprintf(stderr, ...)andfflush(stdout)with an example of handlingfopenfailures. - Example Answer:
File Modes in C File modes determine how a file is opened for reading/writing.
ropens for reading (file must exist),wfor writing (creates/truncates),afor appending (writes at end), andr+for both reading and writing. For example,fopen("log.txt", "a")appends new transactions tolog.txtwithout overwriting existing data, as used in eSewa’s transaction logging system.
- File Modes: Define each mode (
For Programming Questions (10 Marks)
- Structure Your Code:
- Include
<stdio.h>. - Declare variables with meaningful names.
- Use comments to explain steps (e.g.,
// Open file in append mode). - Handle errors (e.g., check
fopenreturn value).
- Include
- Example Question: "Write a program to read 5 student names and CGPA from the user and write them to a file
students.txtin append mode."#include <stdio.h> int main() { FILE *fp = fopen("students.txt", "a"); if (fp == NULL) { printf("Error opening file!\n"); return 1; } for (int i = 0; i < 5; i++) { char name[50]; float cgpa; printf("Enter name and CGPA: "); scanf("%s %f", name, &cgpa); fprintf(fp, "%s, %.2f\n", name, cgpa); } fclose(fp); return 0; }
- Structure Your Code:
For Trace Tables (5 Marks)
- Show initial state, after each operation, and final output.
- Example: For the loan interest program above, include a table with columns for each variable and rows for each step (input → calculation → output).
Real-World Tie-In (Bonus Marks)
- Always relate your answer to a Nepali context (e.g., eSewa, Daraz, Ncell). For example:
"In Daraz’s order processing system, formatted I/O (
scanf/printf) is used to parse customer orders fromorders.txtand update inventory files. Theamode ensures order history is preserved for analytics."
- Always relate your answer to a Nepali context (e.g., eSewa, Daraz, Ncell). For example:
Key Formula to Remember For monthly interest calculation:
Based on the PU BE Computer (PU) syllabus for Programming In C, unit 3.
Discussion
Loading…