Errno Explorer
C
Hard
2 views
Problem Description
Make system calls (write file operations) fail deliberately. Print the value of errno and the message from strerror() on each failure. Understand the pattern.
Official Solution
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
void print_error(const char *msg)
{
printf("%sn", msg);
printf(" errno = %dn", errno);
printf(" strerror = %snn", strerror(errno));
}
int main(void)
{
int fd;
ssize_t bytes;
/* 1. open() failure: file does not exist */
fd = open("this_file_does_not_exist.txt", O_RDONLY);
if (fd == -1) {
print_error("open() failed (nonexistent file)");
}
/* 2. write() failure: invalid file descriptor */
bytes = write(-1, "hello", 5);
if (bytes == -1) {
print_error("write() failed (invalid file descriptor)");
}
/* 3. open() failure: permission denied (likely) */
fd = open("/root/secret.txt", O_WRONLY);
if (fd == -1) {
print_error("open() failed (permission denied)");
}
/* 4. write() failure: writing to read-only file */
fd = open("readonly.txt", O_RDONLY | O_CREAT, 0444);
if (fd != -1) {
bytes = write(fd, "test", 4);
if (bytes == -1) {
print_error("write() failed (read-only file)");
}
close(fd);
}
return 0;
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!