Bird
Raised Fist0
Cprogramming~20 mins

Opening and closing files - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
File Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this C code when opening a file?

Consider the following C code snippet that attempts to open a file named data.txt in read mode. What will be printed if the file does not exist?

C
#include <stdio.h>

int main() {
    FILE *fp = fopen("data.txt", "r");
    if (fp == NULL) {
        printf("File not found\n");
    } else {
        printf("File opened successfully\n");
        fclose(fp);
    }
    return 0;
}
AFile not found
BRuntime error
CCompilation error
DFile opened successfully
Attempts:
2 left
💡 Hint

Think about what happens when you try to open a file for reading that does not exist.

❓ Predict Output
intermediate
2:00remaining
What happens if you try to close a file pointer that is NULL?

Look at this C code snippet. What will happen when it runs?

C
#include <stdio.h>

int main() {
    FILE *fp = NULL;
    fclose(fp);
    printf("Closed file pointer\n");
    return 0;
}
APrints "Closed file pointer" without error
BCauses a segmentation fault or runtime error
CCompilation error due to fclose argument
DPrints nothing and exits
Attempts:
2 left
💡 Hint

Consider what happens if you try to close a file pointer that was never opened.

🔧 Debug
advanced
3:00remaining
Why does this code fail to write to the file?

The following code tries to open a file for writing and write a string. However, the file remains empty after running. What is the problem?

C
#include <stdio.h>

int main() {
    FILE *fp = fopen("output.txt", "w");
    if (fp == NULL) {
        printf("Failed to open file\n");
        return 1;
    }
    fputs("Hello, world!", fp);
    // Missing fclose here
    return 0;
}
Afputs requires a newline character to write
BThe file is opened in write mode but should be append mode
CThe string "Hello, world!" is not null-terminated
DThe file is not closed, so output is not flushed to disk
Attempts:
2 left
💡 Hint

Think about what happens to buffered output if the file is not closed.

📝 Syntax
advanced
2:00remaining
Which option correctly opens a file for appending text?

Choose the correct C code line that opens a file named log.txt for appending text data.

AFILE *fp = fopen("log.txt", "a");
BFILE *fp = fopen("log.txt", "x");
CFILE *fp = fopen("log.txt", "w+");
DFILE *fp = fopen("log.txt", "r+");
Attempts:
2 left
💡 Hint

Appending means adding data to the end without deleting existing content.

🚀 Application
expert
3:00remaining
How many times is the file opened and closed in this program?

Analyze the following C program. How many times does it open and close the file test.txt?

C
#include <stdio.h>

void write_once() {
    FILE *fp = fopen("test.txt", "w");
    if (fp) {
        fputs("First write\n", fp);
        fclose(fp);
    }
}

void write_twice() {
    FILE *fp = fopen("test.txt", "a");
    if (fp) {
        fputs("Second write\n", fp);
        fclose(fp);
    }
}

int main() {
    write_once();
    write_twice();
    return 0;
}
AThe file is opened twice but closed once
BThe file is opened once and closed once
CThe file is opened and closed twice
DThe file is opened once but closed twice
Attempts:
2 left
💡 Hint

Count each fopen and fclose call that executes.

Practice

(1/5)
1. What does the fopen function do in C programming?
easy
A. It closes an open file stream.
B. It opens a file and returns a pointer to the file stream.
C. It reads data from a file.
D. It writes data to a file.

Solution

  1. Step 1: Understand the purpose of fopen

    The fopen function is used to open a file and returns a pointer to the file stream if successful.
  2. Step 2: Differentiate fopen from other file functions

    Functions like fclose close files, fread reads data, and fwrite writes data. Only fopen opens files.
  3. Final Answer:

    It opens a file and returns a pointer to the file stream. -> Option B
  4. Quick Check:

    fopen = open file pointer [OK]
Hint: fopen opens files, fclose closes them [OK]
Common Mistakes:
  • Confusing fopen with fclose
  • Thinking fopen reads or writes data
  • Not knowing fopen returns NULL on failure
2. Which of the following is the correct syntax to open a file named "data.txt" for writing in C?
easy
A. FILE *fp = fopen("data.txt", "w");
B. FILE *fp = fopen("data.txt", "r");
C. FILE *fp = open("data.txt", "w");
D. FILE fp = fopen("data.txt", "w");

Solution

  1. Step 1: Identify correct fopen syntax

    The correct syntax uses FILE * pointer and fopen with filename and mode as strings.
  2. Step 2: Check mode for writing

    Mode "w" opens the file for writing. "r" is for reading, and open is not a standard C function for files.
  3. Final Answer:

    FILE *fp = fopen("data.txt", "w"); -> Option A
  4. Quick Check:

    fopen + "w" = open for writing [OK]
Hint: Use FILE * and fopen with mode "w" to write [OK]
Common Mistakes:
  • Using open instead of fopen
  • Declaring FILE variable instead of pointer
  • Using wrong mode like "r" for writing
3. What will be the output of the following C code snippet?
FILE *fp = fopen("nonexistent.txt", "r");
if (fp == NULL) {
    printf("File not found\n");
} else {
    printf("File opened successfully\n");
    fclose(fp);
}
medium
A. File opened successfully
B. No output
C. File not found
D. Compilation error

Solution

  1. Step 1: Understand fopen with "r" mode on nonexistent file

    Opening a file for reading with "r" mode returns NULL if the file does not exist.
  2. Step 2: Check the if condition

    The code checks if fp == NULL, then prints "File not found". Since file does not exist, this condition is true.
  3. Final Answer:

    File not found -> Option C
  4. Quick Check:

    fopen returns NULL if file missing [OK]
Hint: fopen returns NULL if file missing in "r" mode [OK]
Common Mistakes:
  • Assuming fopen creates file in "r" mode
  • Not checking for NULL before using file pointer
  • Expecting "File opened successfully" always
4. Identify the error in the following code snippet:
FILE *fp;
fp = fopen("file.txt", "w");
printf("File opened\n");
// Missing fclose here
medium
A. fopen mode "w" is incorrect
B. File pointer is not checked for NULL
C. printf statement is incorrect
D. fclose is missing to close the file

Solution

  1. Step 1: Check fopen usage and mode

    The fopen call with mode "w" is correct to open file for writing.
  2. Step 2: Identify missing fclose

    The code opens the file but never closes it with fclose, which can cause resource leaks.
  3. Final Answer:

    fclose is missing to close the file -> Option D
  4. Quick Check:

    Always fclose after fopen [OK]
Hint: Always close files with fclose after opening [OK]
Common Mistakes:
  • Ignoring fclose causes resource leaks
  • Not checking fopen return value
  • Thinking printf affects file handling
5. You want to append text to an existing file "log.txt" safely. Which code snippet correctly opens the file, checks for errors, writes "Hello\n", and closes the file?
hard
A. FILE *fp = fopen("log.txt", "a"); if (fp == NULL) { perror("Error opening file"); } else { fprintf(fp, "Hello\n"); fclose(fp); }
B. FILE *fp = fopen("log.txt", "w"); if (fp != NULL) { fprintf(fp, "Hello\n"); fclose(fp); }
C. FILE *fp = fopen("log.txt", "r"); fprintf(fp, "Hello\n"); fclose(fp);
D. FILE *fp = fopen("log.txt", "a"); fprintf(fp, "Hello\n"); // no fclose

Solution

  1. Step 1: Choose correct mode for appending

    Mode "a" opens file for appending without erasing existing content.
  2. Step 2: Check for NULL and handle errors

    Always check if fopen returns NULL before writing. Use perror to show error if NULL.
  3. Step 3: Write and close file properly

    Use fprintf to write text and fclose to close file to avoid leaks.
  4. Final Answer:

    FILE *fp = fopen("log.txt", "a"); if (fp == NULL) { perror("Error opening file"); } else { fprintf(fp, "Hello\n"); fclose(fp); } -> Option A
  5. Quick Check:

    Append mode + check NULL + fclose = safe file write [OK]
Hint: Use "a" mode, check NULL, fclose after writing [OK]
Common Mistakes:
  • Using "w" mode erases file instead of appending
  • Not checking fopen return value before writing
  • Forgetting to close file with fclose
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