Bird
Raised Fist0
Cprogramming~20 mins

Writing to files in C - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
File Writing Master
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 program writing to a file?

Consider the following C code that writes to a file named output.txt. What will be the content of the file after running this program?

C
#include <stdio.h>

int main() {
    FILE *fp = fopen("output.txt", "w");
    if (fp == NULL) {
        return 1;
    }
    fprintf(fp, "Hello\n");
    fprintf(fp, "World\n");
    fclose(fp);
    return 0;
}
A
The file contains:
Hello
World
B
The file contains:
HelloWorld
CThe program crashes and no file is created
DThe file is empty
Attempts:
2 left
💡 Hint

Look at how fprintf is used with newline characters.

❓ Predict Output
intermediate
2:00remaining
What error does this code produce when writing to a file?

What error will this C code produce when executed?

C
#include <stdio.h>

int main() {
    FILE *fp = fopen("readonly.txt", "r");
    fprintf(fp, "Trying to write\n");
    fclose(fp);
    return 0;
}
ASegmentation fault at fprintf
BRuntime error: writing to a file opened in read mode
CNo error, file is written successfully
DCompilation error: fprintf requires a writable file pointer
Attempts:
2 left
💡 Hint

Think about the mode used to open the file and what fprintf expects.

🔧 Debug
advanced
2:00remaining
Why does this file writing code produce no output in the file?

The following C code is supposed to write "Data" to data.txt, but the file remains empty after running. What is the cause?

C
#include <stdio.h>

int main() {
    FILE *fp = fopen("data.txt", "w");
    if (fp == NULL) {
        return 1;
    }
    fputs("Data", fp);
    // Missing fclose(fp);
    return 0;
}
AThe file pointer is NULL, so nothing is written
BThe file is opened in write mode but no data is written
Cfputs does not write to files, only to stdout
DThe file is not closed, so output is buffered and not flushed to disk
Attempts:
2 left
💡 Hint

Think about how buffered output works and what happens if you don't close the file.

📝 Syntax
advanced
2:00remaining
Which option contains a syntax error in file writing code?

Identify the option that contains a syntax error preventing compilation.

AFILE *fp = fopen("file.txt", "w") if (fp == NULL) { return 1; } fprintf(fp, "Hello"); fclose(fp);
BFILE *fp = fopen("file.txt", "w"); if (fp == NULL) { return 1; } fprintf(fp, "Hello"); fclose(fp);
CFILE *fp = fopen("file.txt", "w"); if (fp != NULL) { fprintf(fp, "Hello"); fclose(fp); }
D;)pf(esolcf ;)"olleH" ,pf(ftnirpf } ;1 nruter { )LLUN == pf( fi ;)"w" ,"txt.elif"(nepof = pf* ELIF
Attempts:
2 left
💡 Hint

Look carefully for missing punctuation in the code.

🚀 Application
expert
2:00remaining
How many bytes are written to the file by this program?

This C program writes a string to a file. How many bytes will the file contain after running?

C
#include <stdio.h>

int main() {
    FILE *fp = fopen("test.txt", "w");
    if (!fp) return 1;
    const char *str = "Line1\nLine2\n";
    int count = fprintf(fp, "%s", str);
    fclose(fp);
    return 0;
}
A10 bytes
B11 bytes
C12 bytes
D13 bytes
Attempts:
2 left
💡 Hint

Count all characters including newline characters in the string.

Practice

(1/5)
1. What does the mode "w" mean when used with fopen in C?
easy
A. Open a file for writing, creating it if it doesn't exist, or overwriting if it does.
B. Open a file for reading only.
C. Open a file for appending data at the end.
D. Open a file in binary mode for reading and writing.

Solution

  1. Step 1: Understand fopen modes

    The mode "w" in fopen means open for writing. If the file exists, it will be overwritten. If it doesn't exist, it will be created.
  2. Step 2: Compare with other modes

    Other modes like "r" are for reading, "a" for appending, and "wb" for binary write. "w" specifically means write with overwrite or create.
  3. Final Answer:

    Open a file for writing, creating it if it doesn't exist, or overwriting if it does. -> Option A
  4. Quick Check:

    fopen mode "w" = write with overwrite [OK]
Hint: Remember: "w" means write and overwrite file [OK]
Common Mistakes:
  • Confusing "w" with "a" (append mode)
  • Thinking "w" opens file for reading
  • Assuming "w" preserves existing content
2. Which of the following is the correct way 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 = fopen("data.txt", "a");
D. FILE *fp = open("data.txt", "w");

Solution

  1. Step 1: Identify correct function and mode

    In C, to open a file for writing, use fopen with mode "w". The function is fopen, not open.
  2. Step 2: Check each option

    FILE *fp = fopen("data.txt", "r"); uses mode "r" (read), not writing. FILE *fp = fopen("data.txt", "a"); uses "a" (append). FILE *fp = open("data.txt", "w"); uses open, which is not standard C file open function.
  3. Final Answer:

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

    Use fopen with "w" to write [OK]
Hint: Use fopen with "w" to write files in C [OK]
Common Mistakes:
  • Using open() instead of fopen()
  • Using wrong mode like "r" or "a"
  • Forgetting to use double quotes around filename
3. What will be the output in the file "output.txt" after running this code?
FILE *fp = fopen("output.txt", "w");
fprintf(fp, "Hello %s!", "World");
fclose(fp);
medium
A. World!
B. Hello %s!
C. Hello World!
D. Compilation error

Solution

  1. Step 1: Understand fprintf usage

    fprintf writes formatted text to the file. The format string "Hello %s!" expects a string argument, which is "World" here.
  2. Step 2: Determine file content

    The file will contain the formatted string with %s replaced by "World", so the file content is "Hello World!".
  3. Final Answer:

    Hello World! -> Option C
  4. Quick Check:

    fprintf formats string correctly [OK]
Hint: fprintf formats and writes text to file [OK]
Common Mistakes:
  • Thinking %s prints literally
  • Forgetting to pass argument for %s
  • Assuming fprintf prints to console
4. Identify the error in this code snippet that writes "Test" to a file:
FILE *fp;
fp = fopen("test.txt", "w");
fprintf(fp, "Test");
medium
A. fopen mode "w" is incorrect for writing
B. File name should be a variable, not a string literal
C. fprintf syntax is wrong, needs format specifier
D. Missing fclose(fp) to close the file

Solution

  1. Step 1: Check file opening and writing

    The file is opened correctly with fopen and mode "w". fprintf syntax is correct to write "Test".
  2. Step 2: Check for missing file closure

    The code does not call fclose(fp), which is necessary to close the file and flush buffers properly.
  3. Final Answer:

    Missing fclose(fp) to close the file -> Option D
  4. Quick Check:

    Always close files with fclose [OK]
Hint: Always fclose after writing to file [OK]
Common Mistakes:
  • Forgetting fclose causes data loss
  • Confusing fopen modes
  • Thinking fprintf needs format specifier always
5. You want to write multiple lines to a file "log.txt" in C. Which code snippet correctly writes these lines and ensures the file is properly handled?
1) FILE *fp = fopen("log.txt", "w");
fprintf(fp, "Line 1\n");
fprintf(fp, "Line 2\n");
fclose(fp);

2) FILE *fp = fopen("log.txt", "r");
fprintf(fp, "Line 1\n");
fclose(fp);

3) FILE *fp = fopen("log.txt", "w");
fprintf(fp, "Line 1\nLine 2\n");
// missing fclose

4) FILE *fp = fopen("log.txt", "a");
fprintf(fp, "Line 1\n");
fclose(fp);
hard
A. Options 1 and 4
B. Option 1 only
C. Option 3 only
D. Option 2 only

Solution

  1. Step 1: Analyze each option's correctness

    Option 1 opens file with "w" (write), writes two lines separately, and closes file properly. This is correct.
  2. Step 2: Check other options

    Option 2 opens with "r" (read), so writing causes error. Option 3 writes lines but misses fclose, risking data loss. Option 4 opens with "a" (append), writes only one line, but the goal is multiple lines.
  3. Final Answer:

    Option 1 only -> Option B
  4. Quick Check:

    "w" + multiple fprintf + fclose [OK]
Hint: Use "w" mode and always fclose [OK]
Common Mistakes:
  • Using "r" mode when writing
  • Forgetting fclose after writing
  • Not understanding difference between "w" and "a"
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