Linux c write files

write(2) — Linux man page

write() writes up to count bytes from the buffer pointed buf to the file referred to by the file descriptor fd.

The number of bytes written may be less than count if, for example, there is insufficient space on the underlying physical medium, or the RLIMIT_FSIZE resource limit is encountered (see setrlimit(2)), or the call was interrupted by a signal handler after having written less than count bytes. (See also pipe(7).)

For a seekable file (i.e., one to which lseek(2) may be applied, for example, a regular file) writing takes place at the current file offset, and the file offset is incremented by the number of bytes actually written. If the file was open(2)ed with O_APPEND, the file offset is first set to the end of the file before writing. The adjustment of the file offset and the write operation are performed as an atomic step.

POSIX requires that a read(2) which can be proved to occur after a write() has returned returns the new data. Note that not all file systems are POSIX conforming.

Return Value

On success, the number of bytes written is returned (zero indicates nothing was written). On error, -1 is returned, and errno is set appropriately.

If count is zero and fd refers to a regular file, then write() may return a failure status if one of the errors below is detected. If no errors are detected, 0 will be returned without causing any other effect. If count is zero and fd refers to a file other than a regular file, the results are not specified.

Errors

EAGAIN The file descriptor fd refers to a file other than a socket and has been marked nonblocking (O_NONBLOCK), and the write would block. EAGAIN or EWOULDBLOCK The file descriptor fd refers to a socket and has been marked nonblocking (O_NONBLOCK), and the write would block. POSIX.1-2001 allows either error to be returned for this case, and does not require these constants to have the same value, so a portable application should check for both possibilities. EBADF fd is not a valid file descriptor or is not open for writing. EDESTADDRREQ fd refers to a datagram socket for which a peer address has not been set using connect(2). EDQUOT The user’s quota of disk blocks on the file system containing the file referred to by fd has been exhausted. EFAULT buf is outside your accessible address space. EFBIG An attempt was made to write a file that exceeds the implementation-defined maximum file size or the process’s file size limit, or to write at a position past the maximum allowed offset. EINTR The call was interrupted by a signal before any data was written; see signal(7). EINVAL fd is attached to an object which is unsuitable for writing; or the file was opened with the O_DIRECT flag, and either the address specified in buf, the value specified in count, or the current file offset is not suitably aligned. EIO A low-level I/O error occurred while modifying the inode. ENOSPC The device containing the file referred to by fd has no room for the data. EPIPE fd is connected to a pipe or socket whose reading end is closed. When this happens the writing process will also receive a SIGPIPE signal. (Thus, the write return value is seen only if the program catches, blocks or ignores this signal.)

Читайте также:  Linux поднять локальный сервер

Other errors may occur, depending on the object connected to fd.

Conforming to

Under SVr4 a write may be interrupted and return EINTR at any point, not just before any data is written.

Notes

A successful return from write() does not make any guarantee that data has been committed to disk. In fact, on some buggy implementations, it does not even guarantee that space has successfully been reserved for the data. The only way to be sure is to call fsync(2) after you are done writing all your data.

If a write() is interrupted by a signal handler before any bytes are written, then the call fails with the error EINTR; if it is interrupted after at least one byte has been written, the call succeeds, and returns the number of bytes written.

See Also

close(2), fcntl(2), fsync(2), ioctl(2), lseek(2), open(2), pwrite(2), read(2), select(2), writev(2), fwrite(3)

Источник

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

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.

Читайте также:  Лабораторная работа настройка linux

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

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:

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 ) ;

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:

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

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

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.

Читайте также:  Telegram share screen linux

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:

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.

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

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

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).

Источник

Оцените статью
Adblock
detector