Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to open a file named "data.txt" for reading.
C
#include <stdio.h> int main() { FILE *file = fopen("data.txt", [1]); if (file == NULL) { printf("Failed to open file.\n"); 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 erases content.
Using "a" which opens the file for appending.
✗ Incorrect
To read from a file, you open it with mode "r".
2fill in blank
mediumComplete the code to read a single character from the file.
C
#include <stdio.h> int main() { FILE *file = fopen("data.txt", "r"); if (file == NULL) { return 1; } int ch = [1](file); if (ch != EOF) { printf("Character read: %c\n", ch); } fclose(file); return 0; }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using
fputc which writes a character to a file.Using
fgets which reads a string, not a single character.✗ Incorrect
fgetc reads a single character from a file.
3fill in blank
hardFix the error in the code to read a line from the file into buffer.
C
#include <stdio.h> int main() { char buffer[100]; FILE *file = fopen("data.txt", "r"); if (file == NULL) { return 1; } if ([1](buffer, 100, file) != NULL) { printf("Line: %s", buffer); } fclose(file); return 0; }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using
fgetc which reads only one character.Using
fread which reads raw bytes and needs size parameters.✗ Incorrect
fgets reads a line from a file into a buffer.
4fill in blank
hardFill both blanks to read the file character by character until EOF.
C
#include <stdio.h> int main() { FILE *file = fopen("data.txt", "r"); if (file == NULL) { return 1; } int ch; while ((ch = [1](file)) [2] EOF) { putchar(ch); } fclose(file); return 0; }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using
fputc which writes characters.Using
== which would stop at the first character.✗ Incorrect
Use fgetc to read each character and loop while it is not EOF.
5fill in blank
hardFill all three blanks to read integers from a file until fscanf fails.
C
#include <stdio.h> int main() { FILE *file = fopen("numbers.txt", "r"); if (file == NULL) { return 1; } int num; while ([1](file, [2], &num) == [3]) { printf("Number: %d\n", num); } fclose(file); return 0; }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using
fgets which reads strings, not formatted integers.Checking for return value 0 or EOF instead of 1.
✗ Incorrect
fscanf reads formatted input; "%d" specifies integer format; it returns 1 when one item is successfully read.