Javascript required
Skip to content Skip to sidebar Skip to footer

How to Read From File Descriptor in C

The Open Group Base Specifications Issue vi
IEEE Std 1003.1, 2004 Edition
Copyright © 2001-2004 The IEEE and The Open Group, All Rights reserved.
A newer edition of this document exists here

Proper noun

pread, read - read from a file

SYNOPSIS

#include <unistd.h>

[XSI] [Option Start] ssize_t pread(int fildes , void * buf , size_t nbyte , off_t commencement ); [Option End]


ssize_t read(int
fildes , void * buf , size_t nbyte );

DESCRIPTION

The read() function shall attempt to read nbyte bytes from the file associated with the open file descriptor, fildes, into the buffer pointed to by buf. The behavior of multiple concurrent reads on the same pipe, FIFO, or last device is unspecified.

Earlier any action described below is taken, and if nbyte is zero, the read() function may detect and render errors as described below. In the absence of errors, or if error detection is not performed, the read() function shall return cypher and have no other results.

On files that support seeking (for example, a regular file), the read() shall start at a position in the file given by the file offset associated with fildes. The file offset shall be incremented by the number of bytes actually read.

Files that do not support seeking-for example, terminals-always read from the current position. The value of a file starting time associated with such a file is undefined.

No data transfer shall occur past the current end-of-file. If the starting position is at or after the end-of-file, 0 shall exist returned. If the file refers to a device special file, the result of subsequent read() requests is implementation-defined.

If the value of nbyte is greater than {SSIZE_MAX}, the result is implementation-defined.

When attempting to read from an empty piping or FIFO:

  • If no process has the pipe open for writing, read() shall render 0 to point end-of-file.

  • If some process has the pipe open for writing and O_NONBLOCK is set, read() shall return -i and prepare errno to [EAGAIN].

  • If some process has the piping open for writing and O_NONBLOCK is clear, read() shall block the calling thread until some data is written or the piping is closed past all processes that had the pipe open for writing.

When attempting to read a file (other than a pipe or FIFO) that supports non-blocking reads and has no information currently available:

  • If O_NONBLOCK is set up, read() shall return -one and set errno to [EAGAIN].

  • If O_NONBLOCK is clear, read() shall block the calling thread until some data becomes available.

  • The apply of the O_NONBLOCK flag has no effect if in that location is some information available.

The read() function reads data previously written to a file. If any portion of a regular file prior to the terminate-of-file has not been written, read() shall return bytes with value 0. For example, lseek() allows the file outset to be gear up across the finish of existing data in the file. If data is later on written at this point, subsequent reads in the gap between the previous end of data and the newly written information shall return bytes with value 0 until data is written into the gap.

Upon successful completion, where nbyte is greater than 0, read() shall marking for update the st_atime field of the file, and shall render the number of bytes read. This number shall never exist greater than nbyte. The value returned may be less than nbyte if the number of bytes left in the file is less than nbyte, if the read() asking was interrupted by a bespeak, or if the file is a pipe or FIFO or special file and has fewer than nbyte bytes immediately available for reading. For case, a read() from a file associated with a final may return i typed line of information.

If a read() is interrupted past a signal before it reads whatsoever data, information technology shall return -1 with errno set to [EINTR].

If a read() is interrupted by a betoken after it has successfully read some data, information technology shall return the number of bytes read.

For regular files, no data transfer shall occur by the offset maximum established in the open file clarification associated with fildes.

If fildes refers to a socket, read() shall be equivalent to recv() with no flags set.

[SIO] [Option Start] If the O_DSYNC and O_RSYNC bits have been gear up, read I/O operations on the file descriptor shall complete as defined by synchronized I/O data integrity completion. If the O_SYNC and O_RSYNC bits have been fix, read I/O operations on the file descriptor shall consummate equally defined by synchronized I/O file integrity completion. [Option End]

[SHM] [Option Start] If fildes refers to a shared memory object, the result of the read() function is unspecified. [Option End]

[TYM] [Option Start] If fildes refers to a typed memory object, the result of the read() role is unspecified. [Option End]

[XSR] [Option Start] A read() from a STREAMS file can read data in three different modes: byte-stream mode, message-nondiscard mode, and message-discard mode. The default shall be byte-stream mode. This can exist changed using the I_SRDOPT ioctl() request, and tin can be tested with I_GRDOPT ioctl(). In byte-stream mode, read() shall retrieve data from the STREAM until as many bytes as were requested are transferred, or until there is no more than data to be retrieved. Byte-stream way ignores message boundaries.

In STREAMS bulletin-nondiscard mode, read() shall retrieve data until as many bytes as were requested are transferred, or until a message boundary is reached. If read() does not retrieve all the data in a message, the remaining information shall be left on the STREAM, and tin be retrieved by the next read() call. Bulletin-discard way also retrieves data until equally many bytes as were requested are transferred, or a message boundary is reached. However, unread data remaining in a bulletin afterwards the read() returns shall be discarded, and shall not be available for a subsequent read(), getmsg(), or getpmsg() call.

How read() handles nil-byte STREAMS messages is determined by the current read mode setting. In byte-stream mode, read() shall accept data until it has read nbyte bytes, or until there is no more than data to read, or until a zero-byte message block is encountered. The read() function shall then render the number of bytes read, and identify the nil-byte bulletin dorsum on the STREAM to be retrieved by the next read(), getmsg(), or getpmsg(). In bulletin-nondiscard style or message-discard mode, a zero-byte bulletin shall return 0 and the message shall exist removed from the STREAM. When a null-byte message is read every bit the first message on a STREAM, the bulletin shall be removed from the STREAM and 0 shall exist returned, regardless of the read fashion.

A read() from a STREAMS file shall return the data in the bulletin at the front of the STREAM head read queue, regardless of the priority band of the message.

By default, STREAMs are in command-normal fashion, in which a read() from a STREAMS file tin can but procedure messages that contain a data part but do non contain a command function. The read() shall fail if a message containing a control part is encountered at the STREAM head. This default action tin can be inverse by placing the STREAM in either control-information mode or command-discard mode with the I_SRDOPT ioctl() command. In command-data manner, read() shall convert any control role to data and pass it to the application earlier passing any data part originally present in the same message. In control-discard fashion, read() shall discard message control parts only return to the procedure whatsoever data part in the message.

In addition, read() shall fail if the STREAM caput had processed an asynchronous fault before the phone call. In this case, the value of errno shall not reflect the outcome of read(), but reflect the prior error. If a hangup occurs on the STREAM beingness read, read() shall proceed to operate normally until the STREAM head read queue is empty. Thereafter, it shall return 0. [Option End]

[XSI] [Option Start] The pread() function shall exist equivalent to read(), except that information technology shall read from a given position in the file without irresolute the file arrow. The first iii arguments to pread() are the same as read() with the addition of a quaternary argument outset for the desired position inside the file. An attempt to perform a pread() on a file that is incapable of seeking shall consequence in an error. [Option End]

Return VALUE

Upon successful completion, read() [XSI] [Option Start] and pread() [Option End] shall return a non-negative integer indicating the number of bytes actually read. Otherwise, the functions shall render -1 and ready errno to signal the mistake.

ERRORS

The read() and [XSI] [Option Start] pread() [Option End] functions shall fail if:

[EAGAIN]
The O_NONBLOCK flag is set for the file descriptor and the thread would exist delayed.
[EBADF]
The fildes argument is not a valid file descriptor open for reading.
[EBADMSG]
[XSR] [Option Start] The file is a STREAM file that is set to control-normal manner and the bulletin waiting to be read includes a control part. [Option End]
[EINTR]
The read functioning was terminated due to the receipt of a betoken, and no data was transferred.
[EINVAL]
[XSR] [Option Start] The STREAM or multiplexer referenced by fildes is linked (directly or indirectly) downstream from a multiplexer. [Option End]
[EIO]
The process is a member of a background process attempting to read from its controlling terminal, the process is ignoring or blocking the SIGTTIN signal, or the process group is orphaned. This error may also be generated for implementation-defined reasons.
[EISDIR]
[XSI] [Option Start] The fildes argument refers to a directory and the implementation does not allow the directory to be read using read() or pread(). The readdir() office should be used instead. [Option End]
[EOVERFLOW]
The file is a regular file, nbyte is greater than 0, the starting position is earlier the terminate-of-file, and the starting position is greater than or equal to the offset maximum established in the open file description associated with fildes.

The read() function shall fail if:

[EAGAIN] or [EWOULDBLOCK]
The file descriptor is for a socket, is marked O_NONBLOCK, and no data is waiting to be received.
[ECONNRESET]
A read was attempted on a socket and the connectedness was forcibly closed by its peer.
[ENOTCONN]
A read was attempted on a socket that is not connected.
[ETIMEDOUT]
A read was attempted on a socket and a transmission timeout occurred.

The read() and [XSI] [Option Start] pread() [Option End] functions may fail if:

[EIO]
A concrete I/O error has occurred.
[ENOBUFS]
Insufficient resources were available in the organization to perform the operation.
[ENOMEM]
Bereft memory was available to fulfill the request.
[ENXIO]
A asking was made of a nonexistent device, or the request was outside the capabilities of the device.

The pread() office shall fail, and the file pointer shall remain unchanged, if:

[EINVAL]
[XSI] [Option Start] The beginning argument is invalid. The value is negative. [Option End]
[EOVERFLOW]
[XSI] [Option Start] The file is a regular file and an attempt was fabricated to read at or beyond the kickoff maximum associated with the file. [Option End]
[ENXIO]
[XSI] [Option Start] A request was outside the capabilities of the device. [Option End]
[ESPIPE]
[XSI] [Option Start] fildes is associated with a pipe or FIFO. [Option End]

The post-obit sections are informative.

EXAMPLES

Reading Data into a Buffer

The post-obit case reads data from the file associated with the file descriptor fd into the buffer pointed to by buf.

          #include <sys/types.h> #include <unistd.h> ... char buf[20]; size_t nbytes; ssize_t bytes_read; int fd; ... nbytes = sizeof(buf); bytes_read = read(fd, buf, nbytes); ...                  

APPLICATION USAGE

None.

RATIONALE

This volume of IEEE Std 1003.i-2001 does not specify the value of the file offset after an error is returned; there are too many cases. For programming errors, such as [EBADF], the concept is meaningless since no file is involved. For errors that are detected immediately, such equally [EAGAIN], conspicuously the pointer should not modify. After an interrupt or hardware mistake, still, an updated value would be very useful and is the behavior of many implementations.

Notation that a read() of zero bytes does not modify st_atime. A read() that requests more than null bytes, but returns zero, shall modify st_atime.

Implementations are immune, but not required, to perform error checking for read() requests of zero bytes.

Input and Output

The use of I/O with large byte counts has always presented issues. Ideas such as lread() and lwrite() (using and returning longs) were considered at one time. The electric current solution is to employ abstract types on the ISO C standard function to read() and write(). The abstract types tin be alleged so that existing functions work, merely can also exist alleged so that larger types tin exist represented in time to come implementations. It is presumed that whatever constraints limit the maximum range of size_t as well limit portable I/O requests to the same range. This volume of IEEE Std 1003.1-2001 also limits the range further by requiring that the byte count be express then that a signed render value remains meaningful. Since the return blazon is also a (signed) abstract blazon, the byte count can be defined past the implementation to be larger than an int can hold.

The standard developers considered adding atomicity requirements to a pipe or FIFO, but recognized that due to the nature of pipes and FIFOs there could be no guarantee of atomicity of reads of {PIPE_BUF} or whatsoever other size that would be an help to applications portability.

This volume of IEEE Std 1003.1-2001 requires that no action be taken for read() or write() when nbyte is nil. This is not intended to have precedence over detection of errors (such every bit invalid buffer pointers or file descriptors). This is consistent with the remainder of this volume of IEEE Std 1003.i-2001, just the phrasing here could be misread to require detection of the zippo case before any other errors. A value of zero is to be considered a correct value, for which the semantics are a no-op.

I/O is intended to be atomic to ordinary files and pipes and FIFOs. Atomic means that all the bytes from a single operation that started out together end up together, without interleaving from other I/O operations. It is a known aspect of terminals that this is not honored, and terminals are explicitly (and implicitly permanently) excepted, making the beliefs unspecified. The behavior for other device types is likewise left unspecified, only the wording is intended to imply that hereafter standards might choose to specify atomicity (or not).

There were recommendations to add format parameters to read() and write() in order to handle networked transfers amongst heterogeneous file system and base hardware types. Such a facility may be required for support by the OSI presentation of layer services. Yet, it was determined that this should correspond with like C-language facilities, and that is beyond the telescopic of this volume of IEEE Std 1003.1-2001. The concept was suggested to the developers of the ISO C standard for their consideration as a possible area for future piece of work.

In 4.iii BSD, a read() or write() that is interrupted by a betoken before transferring any data does not past default return an [EINTR] error, but is restarted. In 4.2 BSD, four.3 BSD, and the 8th Edition, there is an additional function, select(), whose purpose is to pause until specified activeness (information to read, space to write, and so on) is detected on specified file descriptors. Information technology is common in applications written for those systems for select() to exist used before read() in situations (such equally keyboard input) where interruption of I/O due to a point is desired.

The result of which files or file types are interruptible is considered an implementation blueprint outcome. This is ofttimes afflicted primarily past hardware and reliability bug.

At that place are no references to actions taken post-obit an "unrecoverable error". It is considered beyond the scope of this volume of IEEE Std 1003.1-2001 to describe what happens in the case of hardware errors.

Previous versions of IEEE Std 1003.1-2001 immune two very different behaviors with regard to the handling of interrupts. In order to minimize the resulting confusion, information technology was decided that IEEE Std 1003.1-2001 should support merely ane of these behaviors. Historical practice on AT&T-derived systems was to have read() and write() render -1 and set errno to [EINTR] when interrupted afterwards some, but not all, of the data requested had been transferred. All the same, the U.S. Department of Commerce FIPS 151-1 and FIPS 151-two require the historical BSD beliefs, in which read() and write() return the number of bytes actually transferred before the interrupt. If -one is returned when any data is transferred, it is difficult to recover from the error on a seekable device and impossible on a non-seekable device. Near new implementations back up this beliefs. The behavior required by IEEE Std 1003.i-2001 is to return the number of bytes transferred.

IEEE Std 1003.i-2001 does not specify when an implementation that buffers read()s really moves the information into the user-supplied buffer, so an implementation may choose to practise this at the latest possible moment. Therefore, an interrupt arriving earlier may non cause read() to return a partial byte count, but rather to return -ane and ready errno to [EINTR].

Consideration was besides given to combining the two previous options, and setting errno to [EINTR] while returning a short count. However, not only is there no existing practice that implements this, it is likewise contradictory to the thought that when errno is set, the part responsible shall return -one.

FUTURE DIRECTIONS

None.

SEE Too

fcntl(), ioctl(), lseek(), open(), pipe(), readv(), the Base Definitions book of IEEE Std 1003.ane-2001, Affiliate 11, General Last Interface, <stropts.h>, <sys/uio.h>, <unistd.h>

Alter HISTORY

Beginning released in Issue 1. Derived from Issue 1 of the SVID.

Issue 5

The DESCRIPTION is updated for alignment with the POSIX Realtime Extension and the POSIX Threads Extension.

Large File Height extensions are added.

The pread() function is added.

Result 6

The DESCRIPTION and ERRORS sections are updated so that references to STREAMS are marked every bit office of the XSI STREAMS Option Group.

The following new requirements on POSIX implementations derive from alignment with the Unmarried UNIX Specification:

  • The DESCRIPTION now states that if read() is interrupted by a signal afterward it has successfully read some data, it returns the number of bytes read. In Event 3, it was optional whether read() returned the number of bytes read, or whether it returned -one with errno set to [EINTR]. This is a FIPS requirement.

  • In the DESCRIPTION, text is added to indicate that for regular files, no information transfer occurs past the commencement maximum established in the open file description associated with fildes. This modify is to support big files.

  • The [EOVERFLOW] mandatory error condition is added.

  • The [ENXIO] optional error status is added.

Text referring to sockets is added to the DESCRIPTION.

The following changes were made to align with the IEEE P1003.1a draft standard:

  • The effect of reading nil bytes is clarified.

The Clarification is updated for alignment with IEEE Std 1003.1j-2000 past specifying that read() results are unspecified for typed memory objects.

New RATIONALE is added to explain the atomicity requirements for input and output operations.

The following error conditions are added for operations on sockets: [EAGAIN], [ECONNRESET], [ENOTCONN], and [ETIMEDOUT].

The [EIO] error is made optional.

The post-obit error conditions are added for operations on sockets: [ENOBUFS] and [ENOMEM].

The readv() role is split out into a split reference page.

IEEE Std 1003.1-2001/Cor 2-2004, item XSH/TC2/D6/108 is applied, updating the [EAGAIN] error in the ERRORS section from "the process would exist delayed" to "the thread would be delayed".

IEEE Std 1003.1-2001/Cor 2-2004, item XSH/TC2/D6/109 is practical, making an editorial correction in the RATIONALE section.

End of informative text.


UNIX ® is a registered Trademark of The Open Group.
POSIX ® is a registered Trademark of The IEEE.
[ Main Index | XBD | XCU | XSH | XRAT ]

How to Read From File Descriptor in C

Source: https://pubs.opengroup.org/onlinepubs/009604599/functions/read.html