C Programming

Write() Function in C Language

File management in programming is a task that the programmer must be fluent in. Knowledge of the various open, read, and write functions is essential because we always need them to store or dispose the information that are stored in files.

In this Linux Hint article, you will learn how to use the write() function to write the files.

We’ll explain everything about this ella, its syntax, the call method, the input and output arguments, the type of data it accepts in each case, and how to declare it correctly.

Then, we apply what we learned by putting the use of this function into practical examples which we prepared for you with code snippets and images, showing the use of write() in the C language.

In order for you to have a comprehensive knowledge of the use of the write() function, we added a special section which describes the individual errors that can occur when using this function, as well as their detection and identification, so that you have the necessary techniques for a quick solution in case of their occurrence.

Syntax of the Write() Function in C Language

int write(int fd , void *buf, size_t n);

Description of the Write() Function in C Language

The write() function writes to an open file. This function writes the contents of the buffer that is pointed to by “buf” to the file that is specified by its descriptor in the “fd” input argument. The size of the block to be written to the file must be specified in the “n” input argument.

To be able to write with the write() function, the file must be opened with the open() function and specified in the O_RDONLY or O_RDWR attributes. Otherwise, this function has no effect.

If the call is successful, it returns the number of characters that are entered. If an error occurs while writing, it returns a result that is equal to -1. The identification code which indicates the error can be retrieved from the errno global variable which is defined in the “errno.h” header.

Later, you will find a section where we explain how to detect and identify the most common errors of this function.

The write() function is defined in the “unistd.h” header. The flags that define the attributes and mode to open the file are defined in “fcntl.h”. To use the open() and write() functions, you must include these headers in your code as follows:

Let’s pre-create the file that will be written, this is linux, but on Windows you can create the file manually

$ mkdir Documents
$ touch Documents/example.txt

And here is the code:

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

How to Write to a File Using the Write() Function in C Language

In this example, we write an empty text file named “example.txt” that we created earlier in the “Documents” directory.

The first step is to insert the necessary headers. Inside the main() function, open the file with the open() function. To do this, we need to declare the “fd” integer which serves as the file descriptor, and the 1024-character “buf” buffer array that contains the text that we want to write to the file. In this buffer, we store the first paragraph of the GCC man page to write it to the “example.txt” file.

After opening the file with the open() function in read/write mode, we write to the file by calling the write() function and passing the “fd” file descriptor as the first input argument, the “buf” pointer as the second argument, and the size of the string that is contained in the array as the third argument, which we obtain with the strlen() function. Here is the code for this example:

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>

void main () {

    int fd;

    char buffer[1024] = "When you invoke GCC, it normally does preprocessing, compilation, assembly and linking. The overall options allow you to stop this process at an intermediate stage. For example, the -c option says not to run the linker.Then the output consists of object files output by the assembler.";

    fd= open("Documents/example.txt", O_RDWR);

    write(fd, &buffer, strlen(buffer));

    close(fd);
}

In the following figure, we see the compilation and execution of this code together with the opened file that is written by the write() function:

How to Add a Text at the End of a File with the Write() Function in C Language

When a file is opened by specifying the O_WRONLY or O_RDWR flags, the cursor jumps to the first position and starts writing from there.

To add a text at the end of a file, it must be specified by a logical OR operation between the O_WRONLY or O_RDWR flags and the O_ APPEND flag in the input flags argument of the open() function when the file is opened. This way, the cursor is placed at the end of the file and writing starts from there. Also, the attributes and the write mode can be changed once the file is opened with the fcntl() function.

In the following illustration, you can see a code that adds a text at the end of the file that we wrote in the previous example:

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>

void main (){

    int fd;

    char buffer[1024] = "This text is added. This text is added.";

    fd= open("Documents/example.txt", O_RDWR | O_APPEND);

    write(fd, &buffer, strlen(buffer));

    close(fd);

}

The following image shows the added text. As you can see, with this opening method, the write() function starts writing at the position of the last character that is written to the file:

How to Detect and Identify the Errors that Can Occur When Using the Write() Function in the C Language

Using write() can generate various errors. When this happens, this function returns a result that is equal to -1.

The easiest way to determine if an error has occurred is to use an “if” condition where the condition is the return value of -1. Now, let us see how you can use this method to determine if an error has occurred:

int n;

n = write(fd, &buffer , strlen(buffer));

if ( n == -1){

     printf ("An error occurred while trying to write the file.");

}

If the write() function returns with an error, it transitions to the “if” statement and prints the message, “An error occurred while trying to write the file“.

When an error occurs, a numeric code is automatically stored in the errno global variable which is defined in the “errno.h” header. This code can be used to identify the error that occurred.

The following is an excerpt with the errors that the write() function can generate and that are defined in the “errno.h” header, along with a brief description of each error and the associated integer value:

Definition Value in errno Error
EAGAIN 11 Try again.
EBADF 9 Incorrect file number.
EDESTADDRREQ 89 Destination address required.
EDQUOT 122 Exceeded quota.
EFAULT 14 Incorrect address.
EFBIG 27 File too big.
EINTR 4 System call interrupted.
EINVAL 22 Invalid argument.
EIO 5 I/O error.
ENOSPC 28 No space left on device.
EPERM 1 Operation not allowed.

The easiest way to identify an error is to open a switch where the errno variable is the jump condition and each case is an error definition.

Next, let us look at an example where we try to enter a descriptor with a negative sign, resulting in an error. To identify an error, we use the “if” condition that we saw in the previous snippet. To identify it, we open a switch with the three most common errors that this function can produce.

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>

void main(){

    int fd;
    int n;
    char buffer[1024] = "Hello World";

    fd= open("Documents/example.txt", O_RDWR );

    n = write(-2, &buffer, strlen(buffer));

    if (n == -1){

    switch(errno){

          case EBADF:{
                  printf("Bad file number. Error: %i\n", errno);
                  break;}
   
          case EINVAL:{
                   printf("Invalid argument. Error: %i\n", errno);
                   break;}

          case EIO:{
                printf("I/O error . Error: %i\n", errno);
                break;}
    }
 }
}

As we can see in the following figure, the write() function returns an error when an invalid descriptor is passed as an input argument. The value that is retrieved from the errno variable is used as a jump condition which allows us to identify the error when we enter the EBADF case.

Conclusion

In this Linux Hint article, we showed you how to use the write() function to write to the files. We showed you the syntax and the theoretical description of this function. We also explained the error detection and identification methods so that you have the necessary tools and techniques to quickly solve these problems.

To help you see how write() works, we implemented the use of this function in practical examples with codes and images that show the use of this and the other file processing functions.

We also showed you how to select the file open mode to insert a text at the beginning or at the end of the file, and what functions are available to change these attributes.

About the author

Julio Cesar

Julio Cesar is a 42 years old programmer with 8 years of experience in embedded systems development, 6 years developing firmware for user interfaces in C and C++. Additionally he has 2 years of experience developing scripts for network devices and 3 years as developer of high frequency PCB (Printed Circuit Board).