0
0
Cprogramming~10 mins

File pointers 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 "data.txt" for reading.

C
#include <stdio.h>

int main() {
    FILE *fp;
    fp = fopen("data.txt", "[1]");
    if (fp == NULL) {
        printf("Failed to open file.\n");
        return 1;
    }
    fclose(fp);
    return 0;
}
Drag options to blanks, or click blank then click option'
Aa
Bw
Cr
Drw
Attempts:
3 left
💡 Hint
Common Mistakes
Using "w" which overwrites the file instead of reading.
Using "rw" which is not a valid mode in C.
2fill in blank
medium

Complete the code to write the string "Hello" to the file using fprintf.

C
#include <stdio.h>

int main() {
    FILE *fp = fopen("output.txt", "w");
    if (fp == NULL) {
        return 1;
    }
    fprintf(fp, "[1]\n");
    fclose(fp);
    return 0;
}
Drag options to blanks, or click blank then click option'
AWorld
BText
CFile
DHello
Attempts:
3 left
💡 Hint
Common Mistakes
Writing a different string than "Hello".
Forgetting to include the newline character if needed.
3fill in blank
hard

Fix the error in the code to correctly read a line from the file into buffer.

C
#include <stdio.h>

int main() {
    char buffer[100];
    FILE *fp = fopen("input.txt", "r");
    if (fp == NULL) {
        return 1;
    }
    fgets([1], 100, fp);
    printf("%s", buffer);
    fclose(fp);
    return 0;
}
Drag options to blanks, or click blank then click option'
Abuffer
B&buffer
Cfp
D*buffer
Attempts:
3 left
💡 Hint
Common Mistakes
Using &buffer which is a pointer to the array, not a char pointer.
Using *buffer which is the first character, not a pointer.
4fill in blank
hard

Fill both blanks to create a dictionary of word lengths for words longer than 3 characters.

C
#include <stdio.h>
#include <string.h>

int main() {
    char *words[] = {"cat", "elephant", "dog", "giraffe"};
    int lengths[4];
    int count = 0;
    for (int i = 0; i < 4; i++) {
        if (strlen(words[i]) [1] 3) {
            lengths[count] = strlen(words[i]);
            count[2];
        }
    }
    for (int j = 0; j < count; j++) {
        printf("%d\n", lengths[j]);
    }
    return 0;
}
Drag options to blanks, or click blank then click option'
A>
B++
C<
D--
Attempts:
3 left
💡 Hint
Common Mistakes
Using less than operator which selects wrong words.
Decrementing count instead of incrementing.
5fill in blank
hard

Fill all three blanks to create a file pointer, open a file for appending, and write a line.

C
#include <stdio.h>

int main() {
    FILE *[1];
    [1] = fopen("log.txt", "[2]");
    if ([1] == NULL) {
        return 1;
    }
    fprintf([1], "Log entry\n");
    fclose([1]);
    return 0;
}
Drag options to blanks, or click blank then click option'
Afp
Ba
Dr
Attempts:
3 left
💡 Hint
Common Mistakes
Using "r" mode which opens file for reading only.
Using different variable names inconsistently.