1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
// !> 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;
}