read

Reads data from a file or stream.

Library:LibC
Classification:POSIX
Service:File and Directory I/O

Syntax

  #include <unistd.h> 
   
  ssize_t read (
     int      fildes,
     void    *buf,
     size_t   nbytes);
  
  

Parameters

fildes

(IN) Specifies a file descriptor.

buf

(OUT) Points to a buffer to receive the data.

nbytes

(IN) Specifies the number of bytes to read.

Return Values

If successful, returns the number of bytes of data transmitted from the file to the buffer. Normally, this is the number given by the nbytes parameter. When the end-of-file is encountered before the read completes, the return value is less than the number of bytes requested.

If nbytes is 0, returns 0 and may set errno to one of the following. If unsuccessful, returns a -1 and sets errno to one of the following:

Decimal

Constant

Description

4

EBADF

Invalid file descriptor.

5

ENOMEM

Insufficient memory.

24

EAGAIN

The O_NONBLOCK flag is set for the file descriptor, and the resource is temporarily unavailable.

25

ENXIO

The device does not exist.

26

EBADMSG

The data waiting to be read includes a control part.

28

EIO

A physical I/O error has occurred.

54

ECONNRESET

A read was attempted, but the connection was reset by its peer.

57

ENOTCONN

A read was attempted, but the socket is not connected.

60

ETIMEDOUT

A read was attempted, and the connection timed out.

63

EINTR

The read operation was interrupted by a signal

64

EISDIR

The fildes parameter refers to a directory.

81

EOVERFLOW

An attempt was made to read at or beyond the offset maximum associated with the file.

Remarks

The read function returns the number of bytes of data transmitted from the file to the buffer.

The fildes parameter is a value returned by the open, sopen, or creat function. When the file was opened, the access mode must have included either O_RDONLY or O_RDWR.

The data is read starting at the current file position for the file in question. This file position can be determined with the tell function and can be set with the lseek function. If any portion of a regular file prior to the end-of-file has not been written, the read function returns bytes with value 0.

When attempting to read from an empty pipe or FIFO:

  • If no process has the pipe open for writing, the read function returns 0 to indicate end-of-file.

  • If some process has the pipe open for writing and O_NONBLOCK is set, the read function returns -1 and set errno to EAGAIN.

  • If some process has the pipe open for writing and O_NONBLOCK is clear, the read function blocks the calling thread until some data is written or the pipe is closed by all processes that had the pipe open for writing.

See Also