Output To Files (write())#

#include <fcntl.h>
int open(const char *pathname, int flags);
#include <unistd.h>
ssize_t write(int fd, const void buf[.count], size_t count);

open() File For Writing#

  • flags contains O_WRONLY (or O_RDWR for that matter)

  • Unless flags also contains O_APPEND (see Appending To An Existing File, the file will be overwritten starting a position 0

  • File must exist

  • mode is necessary when O_CREAT (and possibly O_EXCL) is used (but see Creating Files for more)

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

int main()
{
    int fd = open("/tmp/somefile", O_WRONLY);
    if (fd == -1) {
        perror("open");
        return 1;
    }
    // ... do something with fd ...
    close(fd);
    return 0;
}

Write One Block Of Bytes#

  • Write 16 bytes (here we add a linefeed character for demonstration purposes)

  • Show how existing content is overwritten

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

int main()
{
    int fd = open("/tmp/somefile", O_WRONLY);
    if (fd == -1) {
        perror("open");
        return 1;
    }

    char bytes[] = "one line of text\n";
    ssize_t nbytes_written = write(fd, bytes, sizeof(bytes));
    if (nbytes_written == -1) {
        perror("write");
        return 1;
    }
    
    close(fd);
    return 0;
}

Write Multiple Blocks Of Bytes#

  • Demonstrate how file position advances by number of bytes written

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

int main()
{
    int fd = open("/tmp/somefile", O_WRONLY);
    if (fd == -1) {
        perror("open");
        return 1;
    }

    char first_line[] = "a fresh line of text\n";
    char second_line[] = "second line\n";

    ssize_t nbytes_written = write(fd, first_line, sizeof(first_line));
    if (nbytes_written == -1) {
        perror("first write");
        return 1;
    }
    nbytes_written = write(fd, second_line, sizeof(second_line));
    if (nbytes_written == -1) {
        perror("second write");
        return 1;
    }
    
    close(fd);
    return 0;
}

Appending To An Existing File#

  • flags contains O_APPEND

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

int main()
{
    int fd = open("/tmp/somefile", O_WRONLY|O_APPEND);
    if (fd == -1) {
        perror("open");
        return 1;
    }

    char third_line[] = "third line\n";

    ssize_t nbytes_written = write(fd, third_line, sizeof(third_line));
    if (nbytes_written == -1) {
        perror("write");
        return 1;
    }
    
    close(fd);
    return 0;
}

Error Conditions#

Use argv[1] like in Input From Files (read()), and …

  • Show “permission denied” (EACCESS)

  • Show “does not exist” (EEXIST)