Search This Blog

Saturday, March 10, 2012

write (C System Call)

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

size_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 null terminated character string of the content to write.
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;
}

No comments:

Post a Comment

Thank you