write (C System Call)

write is a system call that is used to write data out of a buffer.

Required Include Files

#include <unistd.h>

Function Definition

ssize_t write(int fildes, const void *buf, size_t nbytes);
Field Description
int fildes The file descriptor of where to write the output. You can either use a file descriptor obtained from the open system call, or you can use 0, 1, or 2, to refer to standard input, standard output, or standard error, respectively.
const void *buf A pointer to a buffer of at least nbytes bytes, which will be written to the file.
size_t nbytes The number of bytes to write. If smaller than the provided buffer, the output is truncated.
return value Returns the number of bytes that were written. If value is negative, then the system call returned an error.

Code Snippet

Example using standard file descriptors:

#include <unistd.h>
 
int main(void)
{
    if (write(1, "This will be output to standard out\n", 36) != 36) {
        write(2, "There was an error writing to standard out\n", 44);
        return -1;
    }
 
    return 0;
}

Example using a file descriptor:

#include <unistd.h>
#include <fcntl.h>
 
int main(void)
{
    int filedesc = open("testfile.txt", O_WRONLY | O_APPEND);
 
    if (filedesc < 0) {
        return -1;
    }
 
    if (write(filedesc, "This will be output to testfile.txt\n", 36) != 36) {
        write(2, "There was an error writing to testfile.txt\n", 43);
        return -1;
    }
 
    return 0;
}

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License