Complete the code to open a file for reading.
#include <stdio.h> int main() { FILE *file = fopen("data.txt", [1]); if (file == NULL) { perror("Error opening file"); return 1; } fclose(file); return 0; }
"r" opens the file for reading. If the file does not exist, fopen returns NULL.
Complete the code to check if the file pointer is NULL after fopen.
FILE *fp = fopen("log.txt", "r"); if ([1] == NULL) { perror("Failed to open file"); return 1; }
We check if the pointer returned by fopen is NULL to detect errors.
Fix the error in the code to properly close the file only if it was opened.
FILE *f = fopen("input.txt", "r"); if (f == NULL) { perror("Cannot open file"); return 1; } // read file contents [1](f); return 0;
Use fclose() to close a file opened with fopen().
Fill both blanks to read a line safely and check for errors.
#include <stdio.h> char buffer[100]; FILE *file = fopen("notes.txt", "r"); if (file == NULL) { perror("Open failed"); return 1; } if (fgets(buffer, [1], [2]) == NULL) { if (feof(file)) { printf("End of file reached\n"); } else { perror("Read error"); } } fclose(file);
fgets reads up to the buffer size (100) from the file pointer.
Fill all three blanks to write to a file and handle errors properly.
#include <stdio.h> int main() { FILE *fp = fopen("output.txt", [1]); if (fp == NULL) { perror("File open error"); return 1; } if (fprintf(fp, [2], [3]) < 0) { perror("Write error"); fclose(fp); return 1; } fclose(fp); return 0; }
Open the file for writing with "w", use a format string "%s" and pass the string to write.
