Skip to study material
← Question index

QUESTION 04

Explain character, formatted and line-based text file input/output.

5 marks

Answer in brief

Text streams can be processed a character, formatted field or line at a time.

Character operations

Store fgetc’s result in int so it can distinguish EOF from character values. fputc writes one character and reports failure with EOF. The loop while ((ch = fgetc(fp)) != EOF) processes successfully read characters; after it ends, inspect ferror if the difference between an error and normal end matters.

Formatted operations

fprintf writes values using a format string. fscanf interprets input fields and returns the number of assignments completed, or its specified failure indication. Match each conversion to the actual destination type. Bound string conversions and do not assume a failed conversion leaves a usable new value.

Line operations

fgets reads at most capacity - 1 characters and terminates successfully read text. A newline is retained if read. fputs writes the string without adding its own newline. puts, in contrast, writes to stdout and adds a newline.

Choosing a form

Use characters for byte-oriented text transformations, formats for a controlled field layout, and bounded lines when spaces matter. A long input line can span more than one fgets call; decide whether to process chunks or reject an overlong record.

Complexity

Scanning n characters is O(n) character work. A fixed-size line buffer adds O(1) space with respect to the whole file length. The total file need not be loaded into memory. The sample writes two lines and prints them using a checked read loop.

Complete C example

This demonstration creates or replaces its codebhavya_* sample file in the working directory. Run it in a separate test directory. Native binary examples use one compatible implementation.

main.c

Download main.c
/* CodeBhavya | Data Structures AR25 | Learning example */
#include <stdio.h>

int main(void)
{
    const char *path = "codebhavya_text_demo.txt";
    FILE *fp = fopen(path, "w");
    if (fp == NULL) { puts("Open failed"); return 1; }
    if (fputs("First line\nSecond line\n", fp) == EOF) { fclose(fp); puts("Write failed"); return 1; }
    if (fclose(fp) != 0) { puts("Close failed"); return 1; }
    fp = fopen(path, "r");
    if (fp == NULL) { puts("Open failed"); return 1; }
    char line[80];
    while (fgets(line, sizeof line, fp) != NULL) { fputs(line, stdout); }
    int failed = ferror(fp);
    if (fclose(fp) != 0 || failed) { puts("Read/close failed"); return 1; }
    return 0;
}

Sample input and output

The example uses values in the code.

Output

First line
Second line