#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

int main(int argc, char **argv) {
    char *path;
    int fd;
    char buf[] = "Hello, world!\n";
    size_t count = strlen(buf);
    ssize_t bytes_written;
    ssize_t total_bytes_written;

    if (argc < 2) {
        fprintf(stderr, "USAGE: %s file\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    path = argv[1];

    fd = open(path,
              O_WRONLY | O_CREAT | O_TRUNC,
              0644);

    if (-1 == fd) {
        perror("open");
        exit(EXIT_FAILURE);
    }

    bytes_written = write(fd, buf, count);
    if (-1 == bytes_written) {
        perror("write");
        exit(EXIT_FAILURE);
    }

    total_bytes_written = bytes_written;
    while (total_bytes_written < count) {
        total_bytes_written += write(fd,
                buf + total_bytes_written,
                count - total_bytes_written);
    }
    // NOTE: See size_t(3) for how
    // to use size_t with printf().
    printf("Total bytes written %zd\n",
            total_bytes_written);

    if (-1 == close(fd)) {
        perror("close");
        exit(EXIT_FAILURE);
    }

    return EXIT_SUCCESS;
}
