Attempt to open a file in a non-existent directory.
errno = 2 Error message = No such file or directory
#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;
}
#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;
}