Elective Programming In C

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/scanf format 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 and fflush(stdout) to force output.
  • Common pitfalls: Uninitialized variables, buffer overflows, and mismatched format specifiers.
  • Real-world tie: Daraz’s order queue uses fprintf to log transactions; eSewa’s payment records use fopen in 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 file

Visual: 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., fopen returns NULL on failure).
  • Using fflush(stdout) to force output when buffering causes delays.
startscanf fails (e.g., non-numeric input)Input correctedValid InputError State
Debugging flow for scanf input validation

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

  1. eSewa Transaction Logs

    • Idea Used: File handling in append mode ("a").
    • How: Every transaction (e.g., User123 paying 500) is logged to eSewa_transactions.log without 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);
      
  2. 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 to processed_orders.txt (mode "a"). The system uses scanf to parse order details like orderID, product, and quantity.
    • Trace Example:
      • Input file (orders.txt):
        1001,Book,5
        1002,Laptop,1
        
      • After processing, processed_orders.txt appends:
        Order 1001: Book (5) - Shipped
        Order 1002: Laptop (1) - Processing
        
  3. Ncell Billing System

    • Idea Used: File modes ("r+" for updating customer records).
    • How: Customer data (e.g., customerID, balance) is stored in customers.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"]

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

  1. Mismatched Format Specifiers

    • Error: scanf("%d", &float_var) causes undefined behavior.
    • Fix: Use %f for floating-point variables.
    • Example:
      float salary;
      scanf("%f", &salary); // Correct
      
  2. Buffer Overflow in scanf

    • Error: scanf("%s", name) with name declared as char name[5] can overflow if input is longer than 4 characters.
    • Fix: Use scanf("%4s", name) to limit input size or use fgets.
    • Example:
      char name[50];
      scanf("%49s", name); // Leaves space for null terminator
      
  3. Forgetting to Close Files

    • Error: Leaks file descriptors and may corrupt data.
    • Fix: Always use fclose after operations.
    • Example:
      FILE *fp = fopen("data.txt", "r");
      // ... operations ...
      fclose(fp); // Critical!
      

Exam Tip

  1. 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, ...) and fflush(stdout) with an example of handling fopen failures.
    • Example Answer:

      File Modes in C File modes determine how a file is opened for reading/writing. r opens for reading (file must exist), w for writing (creates/truncates), a for appending (writes at end), and r+ for both reading and writing. For example, fopen("log.txt", "a") appends new transactions to log.txt without overwriting existing data, as used in eSewa’s transaction logging system.

  2. For Programming Questions (10 Marks)

    • Structure Your Code:
      1. Include <stdio.h>.
      2. Declare variables with meaningful names.
      3. Use comments to explain steps (e.g., // Open file in append mode).
      4. Handle errors (e.g., check fopen return value).
    • Example Question: "Write a program to read 5 student names and CGPA from the user and write them to a file students.txt in 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;
      }
      
  3. 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).
  4. 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 from orders.txt and update inventory files. The a mode ensures order history is preserved for analytics."


Key Formula to Remember For monthly interest calculation:

Based on the PU BE Computer (PU) syllabus for Programming In C, unit 3.

Discussion

Loading…