0
0
Cprogramming~10 mins

perror and strerror functions - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to print an error message using perror.

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

int main() {
    FILE *fp = fopen("nonexistent.txt", "r");
    if (fp == NULL) {
        [1]("File open error");
    }
    return 0;
}
Drag options to blanks, or click blank then click option'
Aperror
Bprintf
Cstrerror
Dfprintf
Attempts:
3 left
💡 Hint
Common Mistakes
Using printf instead of perror to print error messages.
2fill in blank
medium

Complete the code to get the error message string from errno using strerror.

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

int main() {
    int errnum = 2;
    printf("Error message: %s\n", [1](errnum));
    return 0;
}
Drag options to blanks, or click blank then click option'
Aperror
Bfprintf
Cstrerror_r
Dstrerror
Attempts:
3 left
💡 Hint
Common Mistakes
Using perror instead of strerror to get error string.
3fill in blank
hard

Fix the error in the code to correctly print the error message using perror.

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

int main() {
    FILE *fp = fopen("missing.txt", "r");
    if (fp == NULL) {
        perror([1]);
    }
    return 0;
}
Drag options to blanks, or click blank then click option'
ANULL
B"File error"
Cstrerror(errno)
Derrno
Attempts:
3 left
💡 Hint
Common Mistakes
Passing errno or NULL instead of a string to perror.
4fill in blank
hard

Fill both blanks to create a dictionary-like mapping of error numbers to messages using strerror.

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

int main() {
    int errors[] = {1, 2, 3};
    for (int i = 0; i < 3; i++) {
        printf("Error %d: %s\n", errors[i], [1](errors[i]));
    }
    return [2];
}
Drag options to blanks, or click blank then click option'
Astrerror
Bperror
C0
D1
Attempts:
3 left
💡 Hint
Common Mistakes
Using perror inside the loop or returning 1 instead of 0.
5fill in blank
hard

Fill all three blanks to print an error message using strerror and return an error code.

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

int main() {
    FILE *fp = fopen("file.txt", "r");
    if (fp == NULL) {
        fprintf(stderr, "Error opening file: %s\n", [1]([2]));
        return [3];
    }
    fclose(fp);
    return 0;
}
Drag options to blanks, or click blank then click option'
Aperror
Berrno
C1
Dstrerror
Attempts:
3 left
💡 Hint
Common Mistakes
Using perror inside fprintf or returning 0 on error.