Linux System calls: write

Joshua U
2 min readAug 10, 2023

--

The write system call is used to write data to an open file. It allows you to send data to files, devices, sockets, pipes, and other output destinations. It takes the file descriptor, the data buffer, and the number of bytes to write as arguments. It returns the number of bytes written or -1 on failure. Here’s how the write function is used:

Syntax:

ssize_t write(int fd, const void *buf, size_t count);

Parameters:

  • fd : The file descriptor to which you want to write the data.
  • buf : A pointer to the buffer containing the data to be written.
  • count : The number of bytes to write from the buffer.

Return value:

  • On success the write function returns the number of bytes written. This should be equal to count in most cases.
  • On failure, it returns -1, and you can use the errno variable to determine the specific error.
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>

int main() {
const char *filename = "output.txt";
const char *data = "Hello, world!\n";

// Open the file for writing, create if it doesn't exist
int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (fd == -1) {
perror("Error opening file");
return 1;
}

// Write data to the file
ssize_t bytes_written = write(fd, data, strlen(data));

if (bytes_written == -1) {
perror("Error writing to file");
close(fd); // Close the file before returning on error
return 1;
}

// Close the file
if (close(fd) == -1) {
perror("Error closing file");
return 1;
}

printf("Data written to the file successfully.\n");

return 0;
}

In this example, the program opens a file named output.txt for writing, writes the data Hello, world!\n to the file using the write function, and then closes the file. The write function returns the number of bytes written, which should match the length of the data being written.

--

--

Joshua U

Python Enthusiast, Assistant Professor, Care for developing