0
0
Cprogramming~10 mins

Reading from files in C - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete 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'
A"w"
B"r"
C"a"
D"rw"
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.
2fill in blank
medium

Complete 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'
Afputc
Bfgets
Cfread
Dfgetc
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.
3fill in blank
hard

Fix 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'
Afgets
Bfgetc
Cfread
Dfputc
Attempts:
3 left
💡 Hint
Common Mistakes
Using fgetc which reads only one character.
Using fread which reads raw bytes and needs size parameters.
4fill in blank
hard

Fill 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'
Afgetc
Bfputc
C!=
D==
Attempts:
3 left
💡 Hint
Common Mistakes
Using fputc which writes characters.
Using == which would stop at the first character.
5fill in blank
hard

Fill 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'
Afscanf
B"%d"
C1
Dfgets
Attempts:
3 left
💡 Hint
Common Mistakes
Using fgets which reads strings, not formatted integers.
Checking for return value 0 or EOF instead of 1.