0
0
Cprogramming~10 mins

Writing to 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 named "output.txt" for writing.

C
#include <stdio.h>

int main() {
    FILE *file = fopen("output.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'
Aa
Brw
Cw
Dr
Attempts:
3 left
💡 Hint
Common Mistakes
Using "r" mode which is for reading only.
Using "rw" which is not a valid mode in fopen.
2fill in blank
medium

Complete the code to write the string "Hello, World!" to the file.

C
#include <stdio.h>

int main() {
    FILE *file = fopen("output.txt", "w");
    if (file == NULL) {
        perror("Error opening file");
        return 1;
    }
    fprintf(file, "[1]\n");
    fclose(file);
    return 0;
}
Drag options to blanks, or click blank then click option'
AHello World
BHello, World!
CHello World!
DHello,World!
Attempts:
3 left
💡 Hint
Common Mistakes
Missing the comma or exclamation mark.
Writing without quotes or incorrect string format.
3fill in blank
hard

Fix the error in the code to properly close the file after writing.

C
#include <stdio.h>

int main() {
    FILE *file = fopen("output.txt", "w");
    if (file == NULL) {
        perror("Error opening file");
        return 1;
    }
    fprintf(file, "Hello, World!\n");
    [1](file);
    return 0;
}
Drag options to blanks, or click blank then click option'
Afclose
Bclose
Cfileclose
Dclosefile
Attempts:
3 left
💡 Hint
Common Mistakes
Using close() which is for low-level file descriptors, not FILE pointers.
Using incorrect function names like fileclose or closefile.
4fill in blank
hard

Fill both blanks to write an integer value 42 to the file using fprintf.

C
#include <stdio.h>

int main() {
    FILE *file = fopen("output.txt", "w");
    if (file == NULL) {
        perror("Error opening file");
        return 1;
    }
    int number = 42;
    fprintf(file, "[1]", [2]);
    fclose(file);
    return 0;
}
Drag options to blanks, or click blank then click option'
A"%d"
Bnumber
C"%s"
D42
Attempts:
3 left
💡 Hint
Common Mistakes
Using "%s" which is for strings.
Passing the literal 42 instead of the variable number.
5fill in blank
hard

Fill all three blanks to write multiple lines to a file using fprintf inside a loop.

C
#include <stdio.h>

int main() {
    FILE *file = fopen("output.txt", "w");
    if (file == NULL) {
        perror("Error opening file");
        return 1;
    }
    for (int i = 1; i <= 3; i++) {
        fprintf(file, [1], [2], [3]);
    }
    fclose(file);
    return 0;
}
Drag options to blanks, or click blank then click option'
A"Line %d: %s\n"
Bi
C"Hello"
D"Line %d\n"
Attempts:
3 left
💡 Hint
Common Mistakes
Using a format string with only one placeholder.
Passing arguments in wrong order or missing arguments.