5. io.c example

$ cat -n ostep/code/intro/io.c
     1	#include <stdio.h>
     2	#include <unistd.h>
     3	#include <assert.h>
     4	#include <fcntl.h>
     5	#include <sys/stat.h>
     6	#include <sys/types.h>
     7	#include <string.h>
     8
     9	int main(int argc, char *argv[]) {
    10	    int fd = open("/tmp/file", O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
    11	    assert(fd >= 0);
    12	    char buffer[20];
    13	    sprintf(buffer, "hello world\n");
    14	    int rc = write(fd, buffer, strlen(buffer));
    15	    assert(rc == (strlen(buffer)));
    16	    fsync(fd);
    17	    close(fd);
    18	    return 0;
    19	}
$ ./io
$ cat /tmp/file
hello world
$ ls -ld /tmp
drwxrwxrwt 19 root root 12288 Jun  5 11:43 /tmp
$ ls -l /tmp/file
-rw------- 1 perry perry 12 Jun  5 11:43 /tmp/file
$ ./io
$ chmod 400 /tmp/file
$ ls -l /tmp/file
-r-------- 1 perry perry 12 Jun  5 11:44 /tmp/file
$ ./io
io: io.c:11: main: Assertion `fd >= 0' failed.
Abort (core dumped)
$
--> perror() instead of assert()