0
0
Cprogramming~10 mins

Opening and closing files - 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) {
        perror("Error opening file");
        return 1;
    }
    fclose(file);
    return 0;
}
Drag options to blanks, or click blank then click option'
Ar
Ba
Cx
Dw
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.
Using "x" which creates a new file but fails if it exists.
2fill in blank
medium

Complete the code to close the opened file pointer named "fp".

C
#include <stdio.h>

int main() {
    FILE *fp = fopen("log.txt", "w");
    if (fp == NULL) {
        return 1;
    }
    // Write something to the file
    fprintf(fp, "Hello, file!\n");
    [1](fp);
    return 0;
}
Drag options to blanks, or click blank then click option'
Afopen
Bclose
Copen
Dfclose
Attempts:
3 left
💡 Hint
Common Mistakes
Using close(fp) which is not a standard C function for FILE pointers.
Using fopen(fp) which opens files, not closes.
Using open(fp) which is a system call, not for FILE pointers.
3fill in blank
hard

Fix the error in the code to open a file for appending text.

C
#include <stdio.h>

int main() {
    FILE *file = fopen("output.txt", "[1]");
    if (file == NULL) {
        perror("Failed to open file");
        return 1;
    }
    fprintf(file, "Appending this line.\n");
    fclose(file);
    return 0;
}
Drag options to blanks, or click blank then click option'
Ar
Bw
Ca
Drw
Attempts:
3 left
💡 Hint
Common Mistakes
Using "r" which opens for reading only.
Using "w" which truncates the file.
Using "rw" which is not a valid mode string.
4fill in blank
hard

Fill both blanks to open a file for writing and check if it opened successfully.

C
#include <stdio.h>

int main() {
    FILE *fp = fopen("test.txt", "[1]");
    if (fp == [2]) {
        perror("Cannot open file");
        return 1;
    }
    fclose(fp);
    return 0;
}
Drag options to blanks, or click blank then click option'
Aw
Br
CNULL
D0
Attempts:
3 left
💡 Hint
Common Mistakes
Using "r" mode which opens for reading, not writing.
Checking if fp equals 0 instead of NULL.
Using wrong mode strings.
5fill in blank
hard

Fill all three blanks to open a file for reading, check for errors, and close it.

C
#include <stdio.h>

int main() {
    FILE *file = fopen("input.txt", "[1]");
    if (file == [2]) {
        perror("Error opening file");
        return 1;
    }
    // File operations here
    [3](file);
    return 0;
}
Drag options to blanks, or click blank then click option'
Aw
BNULL
Cfclose
Dr
Attempts:
3 left
💡 Hint
Common Mistakes
Using "w" mode which overwrites the file.
Checking if file pointer equals 0 instead of NULL.
Forgetting to close the file.