Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to open a file for reading.
C
#include <stdio.h> int main() { FILE *file = fopen("data.txt", [1]); if (file == NULL) { perror("Error opening file"); return 1; } fclose(file); return 0; }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using "w" which opens the file for writing and truncates it.
Using "a" which opens the file for appending.
✗ Incorrect
"r" opens the file for reading. If the file does not exist, fopen returns NULL.
2fill in blank
mediumComplete the code to check if the file pointer is NULL after fopen.
C
FILE *fp = fopen("log.txt", "r"); if ([1] == NULL) { perror("Failed to open file"); return 1; }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Dereferencing the pointer before checking if it is NULL.
Checking a member like fp->error which does not exist.
✗ Incorrect
We check if the pointer returned by fopen is NULL to detect errors.
3fill in blank
hardFix the error in the code to properly close the file only if it was opened.
C
FILE *f = fopen("input.txt", "r"); if (f == NULL) { perror("Cannot open file"); return 1; } // read file contents [1](f); return 0;
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using close() which is for low-level file descriptors.
Using made-up functions like closefile or fileclose.
✗ Incorrect
Use fclose() to close a file opened with fopen().
4fill in blank
hardFill both blanks to read a line safely and check for errors.
C
#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);
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using stdin instead of the file pointer.
Using a buffer size smaller than the actual buffer.
✗ Incorrect
fgets reads up to the buffer size (100) from the file pointer.
5fill in blank
hardFill all three blanks to write to a file and handle errors properly.
C
#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; }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Opening the file in "r" mode which is read-only.
Passing the string directly without a format specifier.
✗ Incorrect
Open the file for writing with "w", use a format string "%s" and pass the string to write.