Consider the following C code snippet that attempts to open a file named data.txt in read mode. What will be printed if the file does not exist?
#include <stdio.h> int main() { FILE *fp = fopen("data.txt", "r"); if (fp == NULL) { printf("File not found\n"); } else { printf("File opened successfully\n"); fclose(fp); } return 0; }
Think about what happens when you try to open a file for reading that does not exist.
If the file data.txt does not exist, fopen returns NULL. The program prints "File not found" in this case.
Look at this C code snippet. What will happen when it runs?
#include <stdio.h> int main() { FILE *fp = NULL; fclose(fp); printf("Closed file pointer\n"); return 0; }
Consider what happens if you try to close a file pointer that was never opened.
Calling fclose on a NULL pointer causes undefined behavior, often a segmentation fault or runtime error.
The following code tries to open a file for writing and write a string. However, the file remains empty after running. What is the problem?
#include <stdio.h> int main() { FILE *fp = fopen("output.txt", "w"); if (fp == NULL) { printf("Failed to open file\n"); return 1; } fputs("Hello, world!", fp); // Missing fclose here return 0; }
Think about what happens to buffered output if the file is not closed.
Without calling fclose, the output buffer may not be flushed to the file, so the file remains empty.
Choose the correct C code line that opens a file named log.txt for appending text data.
Appending means adding data to the end without deleting existing content.
Mode "a" opens the file for appending. "r+" opens for reading and writing but does not create the file if missing. "w+" truncates the file. "x" creates a new file but fails if it exists.
Analyze the following C program. How many times does it open and close the file test.txt?
#include <stdio.h> void write_once() { FILE *fp = fopen("test.txt", "w"); if (fp) { fputs("First write\n", fp); fclose(fp); } } void write_twice() { FILE *fp = fopen("test.txt", "a"); if (fp) { fputs("Second write\n", fp); fclose(fp); } } int main() { write_once(); write_twice(); return 0; }
Count each fopen and fclose call that executes.
The function write_once opens and closes the file once. The function write_twice also opens and closes the file once. So total two opens and two closes.