Consider a file named data.txt containing the text "Hello\nWorld". What will this program print?
#include <stdio.h> int main() { FILE *fp = fopen("data.txt", "r"); char buffer[20]; if (fp == NULL) { printf("Error opening file\n"); return 1; } fgets(buffer, sizeof(buffer), fp); printf("%s", buffer); fclose(fp); return 0; }
Remember that fgets reads one line or up to the buffer size.
The fgets function reads one line from the file, including the newline character. Since the first line is "Hello\n", it prints "Hello\n" only.
Given a file numbers.txt with content:
10 20 30
What does this program print?
#include <stdio.h> int main() { FILE *fp = fopen("numbers.txt", "r"); int a, b, c; if (fp == NULL) { printf("Cannot open file\n"); return 1; } fscanf(fp, "%d %d %d", &a, &b, &c); printf("%d %d %d\n", a, b, c); fclose(fp); return 0; }
fscanf reads formatted input from the file.
The fscanf reads three integers from the file in order and stores them in a, b, and c. The program prints them in the same order.
What error will this program produce when run if missing.txt does not exist?
#include <stdio.h> int main() { FILE *fp = fopen("missing.txt", "r"); char c = fgetc(fp); printf("%c\n", c); fclose(fp); return 0; }
Check what happens if fopen returns NULL and you use the pointer without checking.
If the file does not exist, fopen returns NULL. Using fgetc on a NULL pointer causes a segmentation fault (crash).
Given a file text.txt containing "abcde", how many characters will be read and printed by this program?
#include <stdio.h> int main() { FILE *fp = fopen("text.txt", "r"); int count = 0; int c; if (fp == NULL) return 1; while ((c = fgetc(fp)) != EOF) { putchar(c); count++; } fclose(fp); printf("\n%d\n", count); return 0; }
fgetc reads one character at a time until EOF.
The file contains 5 characters: 'a', 'b', 'c', 'd', 'e'. The loop reads all 5 characters and counts them. EOF is not counted.
Assume the file input.txt contains exactly 1234567890.
This program reads a line from input.txt. What will be the value of line after fgets?
#include <stdio.h> int main() { FILE *fp = fopen("input.txt", "r"); char line[10]; if (fp == NULL) return 1; fgets(line, 10, fp); fclose(fp); printf("%s", line); return 0; }
Remember fgets reads up to size-1 characters and adds a null terminator.
The buffer size is 10, so fgets reads up to 9 characters. The file content is "1234567890". It reads the first 9 characters: "123456789" and adds '\0'.