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
The mode "r" opens the file for reading only.
2fill in blank
mediumComplete the code to open a file for writing, creating it if it doesn't exist.
C
#include <stdio.h> int main() { FILE *file = fopen("output.txt", "[1]"); if (file == NULL) { perror("Error opening file"); return 1; } fprintf(file, "Hello, World!\n"); fclose(file); return 0; }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using "r" which opens the file for reading only.
Using "a" which appends instead of overwriting.
✗ Incorrect
The mode "w" opens the file for writing and creates it if it doesn't exist.
3fill in blank
hardFix the error in the code to open a file for appending text.
C
#include <stdio.h> int main() { FILE *file = fopen("log.txt", "[1]"); if (file == NULL) { perror("Error opening file"); return 1; } fprintf(file, "New log entry\n"); fclose(file); return 0; }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using "w" which overwrites the file.
Using "r" which opens for reading only.
✗ Incorrect
The mode "a" opens the file for appending, writing data at the end.
4fill in blank
hardFill both blanks to open a file for reading and writing without truncating it.
C
#include <stdio.h> int main() { FILE *file = fopen("data.txt", "[1][2]"); if (file == NULL) { perror("Error opening file"); return 1; } // Read and write operations fclose(file); return 0; }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using "w+" which truncates the file.
Using "a+" which opens for appending.
✗ Incorrect
The mode "r+" opens the file for both reading and writing without truncating it.
5fill in blank
hardFill both blanks to open a file for writing and reading, truncating it if it exists.
C
#include <stdio.h> int main() { FILE *file = fopen("report.txt", "[1][2]"); if (file == NULL) { perror("Error opening file"); return 1; } // Write and read operations fclose(file); return 0; }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using "r+" which does not truncate the file.
Using "a+" which appends instead of truncating.
✗ Incorrect
The mode "w+" opens the file for both writing (truncating if it exists) and reading.