0
0
Cprogramming~10 mins

File modes 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'
Aw
Brw
Ca
Dr
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 open a file for writing, creating it if it doesn't exist.

C
#include <stdio.h>

int main() {
    FILE *file = fopen("output.txt", "[1]");
    if (file == NULL) {
        perror("Error opening file");
        return 1;
    }
    fprintf(file, "Hello, World!\n");
    fclose(file);
    return 0;
}
Drag options to blanks, or click blank then click option'
Ar
Bw
Ca
Dr+
Attempts:
3 left
💡 Hint
Common Mistakes
Using "r" which opens the file for reading only.
Using "a" which appends instead of overwriting.
3fill in blank
hard

Fix the error in the code to open a file for appending text.

C
#include <stdio.h>

int main() {
    FILE *file = fopen("log.txt", "[1]");
    if (file == NULL) {
        perror("Error opening file");
        return 1;
    }
    fprintf(file, "New log entry\n");
    fclose(file);
    return 0;
}
Drag options to blanks, or click blank then click option'
Aa
Bw
Cr
Dw+
Attempts:
3 left
💡 Hint
Common Mistakes
Using "w" which overwrites the file.
Using "r" which opens for reading only.
4fill in blank
hard

Fill both blanks to open a file for reading and writing without truncating it.

C
#include <stdio.h>

int main() {
    FILE *file = fopen("data.txt", "[1][2]");
    if (file == NULL) {
        perror("Error opening file");
        return 1;
    }
    // Read and write operations
    fclose(file);
    return 0;
}
Drag options to blanks, or click blank then click option'
Ar
Bw
C+
Da
Attempts:
3 left
💡 Hint
Common Mistakes
Using "w+" which truncates the file.
Using "a+" which opens for appending.
5fill in blank
hard

Fill both blanks to open a file for writing and reading, truncating it if it exists.

C
#include <stdio.h>

int main() {
    FILE *file = fopen("report.txt", "[1][2]");
    if (file == NULL) {
        perror("Error opening file");
        return 1;
    }
    // Write and read operations
    fclose(file);
    return 0;
}
Drag options to blanks, or click blank then click option'
Ar
B+
Cw
Da
Attempts:
3 left
💡 Hint
Common Mistakes
Using "r+" which does not truncate the file.
Using "a+" which appends instead of truncating.