Consider the following C code that writes to a file named output.txt. What will be the content of the file after running this program?
#include <stdio.h> int main() { FILE *fp = fopen("output.txt", "w"); if (fp == NULL) { return 1; } fprintf(fp, "Hello\n"); fprintf(fp, "World\n"); fclose(fp); return 0; }
Look at how fprintf is used with newline characters.
The program opens the file in write mode, writes "Hello" followed by a newline, then "World" followed by a newline, then closes the file. So the file contains two lines: "Hello" and "World".
What error will this C code produce when executed?
#include <stdio.h> int main() { FILE *fp = fopen("readonly.txt", "r"); fprintf(fp, "Trying to write\n"); fclose(fp); return 0; }
Think about the mode used to open the file and what fprintf expects.
The file is opened in read mode, so writing to it with fprintf causes a runtime error because the file pointer is not writable.
The following C code is supposed to write "Data" to data.txt, but the file remains empty after running. What is the cause?
#include <stdio.h> int main() { FILE *fp = fopen("data.txt", "w"); if (fp == NULL) { return 1; } fputs("Data", fp); // Missing fclose(fp); return 0; }
Think about how buffered output works and what happens if you don't close the file.
Output to files is buffered. Without calling fclose or fflush, the buffer may not be written to the file, leaving it empty.
Identify the option that contains a syntax error preventing compilation.
Look carefully for missing punctuation in the code.
Option A is missing a semicolon after the fopen call, causing a syntax error.
This C program writes a string to a file. How many bytes will the file contain after running?
#include <stdio.h> int main() { FILE *fp = fopen("test.txt", "w"); if (!fp) return 1; const char *str = "Line1\nLine2\n"; int count = fprintf(fp, "%s", str); fclose(fp); return 0; }
Count all characters including newline characters in the string.
The string "Line1\nLine2\n" has 12 characters: 5 letters + 1 newline + 5 letters + 1 newline = 12 bytes.