The most basic read and write functions for files in C

  • 2020-04-02 03:19:16
  • OfStack

C read() function: file reading function (read data from an open file)
The header file:


#include <unistd.h>

Definition function:


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

Function description: the read () fd refers to the parameter file transfer count bytes buf Pointers to memory. If the parameters of the count is zero, the read () have no effect and returns 0. The return value for the actual number of bytes to read. If it returns 0, said it had reached end-of-file or data that cannot be read, in addition with byte read file to read and write position.

Additional notes:
If read() returns the number of bytes actually read, it is best to compare the return value with the parameter count. The & # 63; Or poison � ead () is read by a signal is interrupted.

When an error occurs, -1 is returned, the error code is stored in the errno, and the file read and write location is not expected.

Error code:

EINTR this call is interrupted by the signal. EAGAIN returns this value if there is no data available when using uninterruptible I/O (O_NONBLOCK). EBADF parameter fd is not a valid file descriptor, or the file is closed.

C write() function: write file function
The header file:


#include <unistd.h>

Definition function:


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

Write () writes the memory referred to by buf to the file referred to by fd in count bytes.

Return value: the number of bytes actually written is returned if write() is successful. When an error occurs, -1 is returned and the error code is stored in the errno.

Error code:

EINTR this call is interrupted by the signal. EAGAIN returns this value if there is no data available when using uninterruptible I/O (O_NONBLOCK). EADF parameter fd is not a valid file descriptor, or the file is closed.


Related articles: