Bird
Raised Fist0
Cprogramming~10 mins

Error handling in files in C - Interactive Code Practice

Choose your learning style10 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.

Practice

(1/5)
1. What does fopen return if it fails to open a file in C?
easy
A. 0
B. An empty string
C. -1
D. NULL

Solution

  1. Step 1: Understand fopen behavior

    The fopen function returns a pointer to a FILE object if successful.
  2. Step 2: Identify failure return value

    If fopen fails (e.g., file not found), it returns NULL to indicate error.
  3. Final Answer:

    NULL -> Option D
  4. Quick Check:

    fopen failure returns NULL [OK]
Hint: Remember: fopen returns NULL on failure, not zero or -1 [OK]
Common Mistakes:
  • Thinking fopen returns 0 on failure
  • Confusing NULL with empty string
  • Assuming fopen throws an error instead of returning NULL
2. Which of the following is the correct way to check if a file was opened successfully in C?
easy
A. if (file != NULL)
B. if (file == 0)
C. if (file == -1)
D. if (file == NULL)

Solution

  1. Step 1: Recall fopen return value on failure

    fopen returns NULL if it fails to open a file.
  2. Step 2: Write correct check for success

    To check if opened successfully, compare the file pointer using file != NULL.
  3. Final Answer:

    if (file != NULL) -> Option A
  4. Quick Check:

    Check file pointer against NULL for success [OK]
Hint: Check if file pointer != NULL to confirm open success [OK]
Common Mistakes:
  • Using 0 or -1 instead of NULL for pointer check
  • Checking if file == NULL to confirm success
  • Confusing integer and pointer comparisons
3. What will be the output of this C code snippet?
#include <stdio.h>
int main() {
    FILE *fp = fopen("nonexistent.txt", "r");
    if (fp == NULL) {
        printf("File open failed\n");
    } else {
        printf("File opened\n");
        fclose(fp);
    }
    return 0;
}
medium
A. File opened
B. File open failed
C. Compilation error
D. No output

Solution

  1. Step 1: fopen tries to open a non-existing file

    The file "nonexistent.txt" does not exist, so fopen returns NULL.
  2. Step 2: Check the if condition and output

    Since fp == NULL is true, the program prints "File open failed".
  3. Final Answer:

    File open failed -> Option B
  4. Quick Check:

    fopen fails, prints failure message [OK]
Hint: If fopen returns NULL, print error message [OK]
Common Mistakes:
  • Assuming file opens successfully
  • Ignoring the NULL check
  • Expecting compilation error due to fopen
4. Identify the error in this code snippet that opens and closes a file:
#include <stdio.h>
int main() {
    FILE *fp = fopen("data.txt", "r");
    if (fp == NULL) {
        printf("Error opening file\n");
    }
    fclose(fp);
    return 0;
}
medium
A. Calling fclose even if fopen failed
B. Incorrect mode in fopen
C. Missing check if fclose succeeded
D. No error, code is correct

Solution

  1. Step 1: Analyze fopen and NULL check

    The code checks if fp == NULL and prints error if true.
  2. Step 2: Check fclose usage

    Even if fp == NULL, the code calls fclose(fp), which is invalid and causes undefined behavior.
  3. Final Answer:

    Calling fclose even if fopen failed -> Option A
  4. Quick Check:

    Only fclose valid file pointers, not NULL [OK]
Hint: Only call fclose if fopen succeeded (fp != NULL) [OK]
Common Mistakes:
  • Calling fclose on NULL pointer
  • Not checking fopen return before fclose
  • Assuming fclose always succeeds without check
5. You want to safely open a file for writing, write "Hello" to it, and close it. Which code snippet correctly handles errors for all steps?
hard
A. #include int main() { FILE *fp = fopen("file.txt", "r"); if (fp == NULL) { perror("Open failed"); return 1; } fprintf(fp, "Hello"); fclose(fp); return 0; }
B. #include int main() { FILE *fp = fopen("file.txt", "w"); fprintf(fp, "Hello"); fclose(fp); return 0; }
C. #include int main() { FILE *fp = fopen("file.txt", "w"); if (fp == NULL) { perror("Open failed"); return 1; } if (fprintf(fp, "Hello") < 0) { perror("Write failed"); fclose(fp); return 1; } if (fclose(fp) != 0) { perror("Close failed"); return 1; } return 0; }
D. #include int main() { FILE *fp = fopen("file.txt", "w"); if (fp == NULL) { printf("Error opening file\n"); } fprintf(fp, "Hello"); fclose(fp); return 0; }

Solution

  1. Step 1: Check fopen return value

    The correct code checks if fopen returns NULL and handles error with perror and exit.
  2. Step 2: Check fprintf return value and fclose return value

    The correct code also checks if fprintf fails (returns negative) and if fclose fails (returns non-zero), handling errors properly.
  3. Final Answer:

    The code that checks fopen, fprintf, and fclose -> Option C
  4. Quick Check:

    Check fopen, fprintf, fclose return values for safe file handling [OK]
Hint: Check fopen, fprintf, fclose return values to handle errors [OK]
Common Mistakes:
  • Not checking fopen return before writing
  • Using wrong mode for writing
  • Ignoring fclose errors
  • Writing without checking fprintf success
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard