0
0
Cprogramming~10 mins

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

Complete 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'
Afp->error
Bfp
C*fp
Dfopen
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.
3fill in blank
hard

Fix 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'
Aclosefile
Bfileclose
Cfclose
Dclose
Attempts:
3 left
💡 Hint
Common Mistakes
Using close() which is for low-level file descriptors.
Using made-up functions like closefile or fileclose.
4fill in blank
hard

Fill 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'
A100
Bfile
Cstdin
D50
Attempts:
3 left
💡 Hint
Common Mistakes
Using stdin instead of the file pointer.
Using a buffer size smaller than the actual buffer.
5fill in blank
hard

Fill 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'
A"w"
B"Hello, World!\n"
C"%s"
D"r"
Attempts:
3 left
💡 Hint
Common Mistakes
Opening the file in "r" mode which is read-only.
Passing the string directly without a format specifier.