banner



How To Use Read In C

The Open Group Base Specifications Issue 6
IEEE Std 1003.1, 2004 Edition
Copyright © 2001-2004 The IEEE and The Open Grouping, 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 start ); [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 up file descriptor, fildes, into the buffer pointed to by buf. The beliefs of multiple concurrent reads on the same pipe, FIFO, or terminal device is unspecified.

Before whatsoever action described below is taken, and if nbyte is goose egg, the read() function may discover and return errors as described below. In the absence of errors, or if error detection is non performed, the read() office shall return zero and have no other results.

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

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

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

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

When attempting to read from an empty pipe or FIFO:

  • If no process has the pipage open for writing, read() shall return 0 to betoken stop-of-file.

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

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

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

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

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

  • The use of the O_NONBLOCK flag has no effect if there is some data available.

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

Upon successful completion, where nbyte is greater than 0, read() shall mark for update the st_atime field of the file, and shall return the number of bytes read. This number shall never be 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 signal, or if the file is a pipe or FIFO or special file and has fewer than nbyte bytes immediately available for reading. For example, a read() from a file associated with a terminal may render 1 typed line of data.

If a read() is interrupted past a bespeak earlier information technology reads any data, it shall return -1 with errno fix to [EINTR].

If a read() is interrupted past a betoken later information technology has successfully read some information, it shall render the number of bytes read.

For regular files, no data transfer shall occur past the offset maximum established in the open file description 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 take been fix, 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 $.25 have been set, read I/O operations on the file descriptor shall consummate as defined past 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 retention object, the effect of the read() function is unspecified. [Option End]

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

In STREAMS message-nondiscard mode, read() shall retrieve information 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 side by side read() telephone call. Message-discard way also retrieves information until every bit many bytes as were requested are transferred, or a message boundary is reached. Nonetheless, unread data remaining in a message after the read() returns shall exist discarded, and shall not be available for a subsequent read(), getmsg(), or getpmsg() call.

How read() handles zip-byte STREAMS messages is determined past the current read mode setting. In byte-stream mode, read() shall accept data until information technology has read nbyte bytes, or until in that location is no more than data to read, or until a zero-byte message block is encountered. The read() office shall then return the number of bytes read, and place the zero-byte message dorsum on the STREAM to be retrieved past the next read(), getmsg(), or getpmsg(). In message-nondiscard way or message-discard mode, a naught-byte message shall render 0 and the message shall be removed from the STREAM. When a zero-byte bulletin is read as the start message on a STREAM, the message shall be removed from the STREAM and 0 shall be returned, regardless of the read style.

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

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

In add-on, read() shall neglect if the STREAM head had candy an asynchronous error before the call. In this case, the value of errno shall not reflect the result of read(), simply reflect the prior error. If a hangup occurs on the STREAM being read, read() shall go along to operate normally until the STREAM caput read queue is empty. Thereafter, information technology shall render 0. [Option End]

[XSI] [Option Start] The pread() role shall be equivalent to read(), except that information technology shall read from a given position in the file without changing the file arrow. The first iii arguments to pread() are the same equally read() with the add-on of a fourth argument offset for the desired position inside the file. An attempt to perform a pread() on a file that is incapable of seeking shall effect in an error. [Option End]

Render 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 return -1 and ready errno to betoken the mistake.

ERRORS

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

[EAGAIN]
The O_NONBLOCK flag is ready for the file descriptor and the thread would be 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 prepare to control-normal mode and the message waiting to be read includes a command function. [Option End]
[EINTR]
The read operation was terminated due to the receipt of a point, 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 procedure is a member of a groundwork process attempting to read from its controlling final, the process is ignoring or blocking the SIGTTIN signal, or the process group is orphaned. This mistake may besides be generated for implementation-defined reasons.
[EISDIR]
[XSI] [Option Start] The fildes argument refers to a directory and the implementation does non let the directory to be read using read() or pread(). The readdir() part should exist used instead. [Option End]
[EOVERFLOW]
The file is a regular file, nbyte is greater than 0, the starting position is before the end-of-file, and the starting position is greater than or equal to the showtime 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 connection was forcibly closed past its peer.
[ENOTCONN]
A read was attempted on a socket that is non continued.
[ETIMEDOUT]
A read was attempted on a socket and a manual timeout occurred.

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

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

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

[EINVAL]
[XSI] [Option Start] The offset statement is invalid. The value is negative. [Option End]
[EOVERFLOW]
[XSI] [Option Start] The file is a regular file and an effort was made to read at or across the offset 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 following sections are informative.

EXAMPLES

Reading Data into a Buffer

The following example 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[twenty]; size_t nbytes; ssize_t bytes_read; int fd; ... nbytes = sizeof(buf); bytes_read = read(fd, buf, nbytes); ...                  

Application USAGE

None.

RATIONALE

This book of IEEE Std 1003.1-2001 does not specify the value of the file commencement afterward an error is returned; there are likewise many cases. For programming errors, such as [EBADF], the concept is meaningless since no file is involved. For errors that are detected immediately, such as [EAGAIN], clearly the arrow should not change. After an interrupt or hardware error, however, an updated value would be very useful and is the behavior of many implementations.

Note that a read() of nil bytes does not alter st_atime. A read() that requests more than goose egg bytes, only returns zero, shall modify st_atime.

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

Input and Output

The utilise of I/O with big byte counts has always presented problems. Ideas such as lread() and lwrite() (using and returning longs) were considered at one time. The electric current solution is to apply abstruse types on the ISO C standard function to read() and write(). The abstract types can be declared and so that existing functions work, but can also be declared so that larger types can exist represented in future implementations. Information technology is presumed that whatever constraints limit the maximum range of size_t also 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 limited and then that a signed return value remains meaningful. Since the return type is as well a (signed) abstract blazon, the byte count can be divers past the implementation to be larger than an int tin can hold.

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

This volume of IEEE Std 1003.one-2001 requires that no action be taken for read() or write() when nbyte is zero. This is non intended to take precedence over detection of errors (such equally invalid buffer pointers or file descriptors). This is consequent with the rest of this volume of IEEE Std 1003.1-2001, only the phrasing here could be misread to require detection of the nil case before whatsoever other errors. A value of cipher is to exist 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. Diminutive ways that all the bytes from a single functioning that started out together terminate upward together, without interleaving from other I/O operations. It is a known attribute of terminals that this is not honored, and terminals are explicitly (and implicitly permanently) excepted, making the behavior unspecified. The beliefs for other device types is likewise left unspecified, but the diction is intended to imply that future standards might choose to specify atomicity (or not).

There were recommendations to add format parameters to read() and write() in gild to handle networked transfers amidst heterogeneous file system and base hardware types. Such a facility may be required for support by the OSI presentation of layer services. However, it was determined that this should correspond with similar C-language facilities, and that is beyond the scope 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 work.

In 4.3 BSD, a read() or write() that is interrupted by a signal earlier transferring whatsoever data does non by default return an [EINTR] fault, but is restarted. In 4.2 BSD, four.3 BSD, and the Eighth Edition, in that location is an additional part, select(), whose purpose is to pause until specified activity (data to read, space to write, and then on) is detected on specified file descriptors. It is common in applications written for those systems for select() to be used before read() in situations (such equally keyboard input) where interruption of I/O due to a betoken is desired.

The issue of which files or file types are interruptible is considered an implementation blueprint outcome. This is frequently affected primarily past hardware and reliability issues.

In that location are no references to actions taken post-obit an "unrecoverable mistake". It is considered beyond the telescopic of this volume of IEEE Std 1003.ane-2001 to describe what happens in the case of hardware errors.

Previous versions of IEEE Std 1003.1-2001 immune ii very different behaviors with regard to the handling of interrupts. In order to minimize the resulting confusion, it was decided that IEEE Std 1003.1-2001 should support only i of these behaviors. Historical practice on AT&T-derived systems was to accept read() and write() render -1 and fix errno to [EINTR] when interrupted afterwards some, simply not all, of the data requested had been transferred. Nonetheless, the U.Due south. Department of Commerce FIPS 151-1 and FIPS 151-2 crave the historical BSD behavior, in which read() and write() return the number of bytes actually transferred before the interrupt. If -1 is returned when whatsoever information is transferred, it is hard to recover from the error on a seekable device and impossible on a not-seekable device. Nearly new implementations support this behavior. The beliefs required by IEEE Std 1003.1-2001 is to return the number of bytes transferred.

IEEE Std 1003.1-2001 does non specify when an implementation that buffers read()due south actually moves the data into the user-supplied buffer, and then an implementation may choose to do this at the latest possible moment. Therefore, an interrupt arriving earlier may not cause read() to return a partial byte count, simply rather to return -1 and set errno to [EINTR].

Consideration was also given to combining the 2 previous options, and setting errno to [EINTR] while returning a brusque count. However, not but is there no existing practise that implements this, information technology is also contradictory to the idea that when errno is set, the function responsible shall return -ane.

Future DIRECTIONS

None.

Run across ALSO

fcntl(), ioctl(), lseek(), open up(), pipe(), readv(), the Base Definitions volume of IEEE Std 1003.1-2001, Chapter xi, General Terminal Interface, <stropts.h>, <sys/uio.h>, <unistd.h>

Change HISTORY

Commencement released in Outcome 1. Derived from Upshot 1 of the SVID.

Issue v

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

Large File Summit extensions are added.

The pread() function is added.

Effect vi

The Description and ERRORS sections are updated then that references to STREAMS are marked as part of the XSI STREAMS Choice Group.

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

  • The DESCRIPTION at present states that if read() is interrupted by a betoken subsequently it has successfully read some data, it returns the number of bytes read. In Issue three, it was optional whether read() returned the number of bytes read, or whether information technology returned -1 with errno fix to [EINTR]. This is a FIPS requirement.

  • In the Clarification, text is added to indicate that for regular files, no information transfer occurs past the offset maximum established in the open up file clarification associated with fildes. This change is to support large files.

  • The [EOVERFLOW] mandatory error condition is added.

  • The [ENXIO] optional error condition is added.

Text referring to sockets is added to the DESCRIPTION.

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

  • The event of reading zilch bytes is clarified.

The DESCRIPTION is updated for alignment with IEEE Std 1003.1j-2000 by 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 atmospheric condition are added for operations on sockets: [EAGAIN], [ECONNRESET], [ENOTCONN], and [ETIMEDOUT].

The [EIO] mistake is fabricated optional.

The following error weather condition are added for operations on sockets: [ENOBUFS] and [ENOMEM].

The readv() role is split out into a separate 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 be delayed" to "the thread would be delayed".

IEEE Std 1003.1-2001/Cor ii-2004, detail XSH/TC2/D6/109 is applied, making an editorial correction in the RATIONALE department.

End of informative text.


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

How To Use Read In C,

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

Posted by: allenthwary.blogspot.com

0 Response to "How To Use Read In C"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel