// !> Reading and writing files with POSIX I/O [fv]
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <stdio.h>
#include <assert.h>
int main(int argc, char **argv) {
char buffer[256];
// open a file for reading
int fd = open("foo.txt", O_RDONLY);
if (fd == -1) {
perror("Failed to open file");
return 1;
}
// read at most 255 bytes and print to the terminal
int bytes_read = read(fd, buffer, 255);
buffer[bytes_read] = '\0';
printf("Read %d bytes:\n%s\n", bytes_read, buffer);
// close the file
close(fd);
// open another file for writing, create it if it doesn't exist, and delete
// its contents (truncate)
// (important: use | - _bitwise_ or to combine flags, not || - logical or)
fd = open(
"foobar.txt",
O_WRONLY | O_CREAT | O_TRUNC,
0664 // mode: rw-rw-r--
);
if (fd == -1) {
perror("Failed to open file");
return 1;
}
// write 5 bytes to the file
int bytes_written = write(fd, buffer, 5);
printf("Written %d bytes\n", bytes_written);
// bytes_read = read(fd, buffer, 256);
//buffer[bytes_read] = '\0';
//printf("Read %d bytes:\n%s\n", bytes_read, buffer);
// close file
close(fd);
return 0;
}