Coninue Read a File in a Function

The Open up Group Base Specifications Result 6
IEEE Std 1003.ane, 2004 Edition
Copyright © 2001-2004 The IEEE and The Open Group, All Rights reserved.
A newer edition of this certificate exists hither

NAME

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 offset ); [Option End]


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

Description

The read() office shall try to read nbyte bytes from the file associated with the open up file descriptor, fildes, into the buffer pointed to by buf. The behavior of multiple concurrent reads on the same piping, FIFO, or terminal device is unspecified.

Before any action described beneath is taken, and if nbyte is aught, the read() function may detect and render errors as described below. In the absence of errors, or if fault detection is non performed, the read() part shall return zero 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 showtime associated with fildes. The file offset shall be incremented by the number of bytes actually read.

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

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

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

When attempting to read from an empty piping or FIFO:

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

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

  • If some procedure has the pipe open for writing and O_NONBLOCK is articulate, read() shall cake the calling thread until some data is written or the pipage is airtight by all processes that had the piping open for writing.

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

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

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

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

The read() function reads data 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 example, lseek() allows the file offset to be set across the cease of existing information in the file. If data is afterwards written at this point, subsequent reads in the gap between the previous finish of information and the newly written data shall return bytes with value 0 until data 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() request was interrupted by a bespeak, or if the file is a piping 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 terminal may render one typed line of data.

If a read() is interrupted by a signal earlier information technology reads any data, it shall render -1 with errno set up to [EINTR].

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

For regular files, no data transfer shall occur by the outset 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 set up, read I/O operations on the file descriptor shall complete every bit divers past synchronized I/O information integrity completion. If the O_SYNC and O_RSYNC bits have been ready, read I/O operations on the file descriptor shall complete every bit 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() office is unspecified. [Option End]

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

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

In STREAMS bulletin-nondiscard way, 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 data shall exist left on the STREAM, and can be retrieved past the adjacent read() call. Message-discard mode also retrieves data until as many bytes as were requested are transferred, or a message boundary is reached. However, unread information remaining in a message afterward the read() returns shall be discarded, and shall not be bachelor for a subsequent read(), getmsg(), or getpmsg() call.

How read() handles nix-byte STREAMS messages is determined by the electric current read mode setting. In byte-stream mode, read() shall have information until it has read nbyte bytes, or until in that location is no more information to read, or until a zippo-byte message block is encountered. The read() function shall then return the number of bytes read, and place the zero-byte message back on the STREAM to be retrieved by the side by side read(), getmsg(), or getpmsg(). In message-nondiscard fashion or message-discard manner, a zero-byte message shall return 0 and the bulletin shall exist removed from the STREAM. When a zero-byte message is read equally the first bulletin on a STREAM, the message shall be removed from the STREAM and 0 shall be returned, regardless of the read mode.

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

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

In addition, read() shall fail if the STREAM head had candy an asynchronous fault earlier the telephone 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 being read, read() shall continue 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 be equivalent to read(), except that it shall read from a given position in the file without changing the file pointer. The beginning 3 arguments to pread() are the aforementioned as read() with the improver of a 4th argument start for the desired position inside the file. An attempt to perform a pread() on a file that is incapable of seeking shall result in an error. [Option End]

RETURN VALUE

Upon successful completion, read() [XSI] [Option Start] and pread() [Option End] shall render a not-negative integer indicating the number of bytes actually read. Otherwise, the functions shall return -i and set up errno to indicate the error.

ERRORS

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

[EAGAIN]
The O_NONBLOCK flag is set for the file descriptor and the thread would be delayed.
[EBADF]
The fildes argument is not a valid file descriptor open up for reading.
[EBADMSG]
[XSR] [Option Start] The file is a STREAM file that is prepare to control-normal way and the message waiting to be read includes a control office. [Option End]
[EINTR]
The read operation was terminated due to the receipt of a point, and no information 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 procedure attempting to read from its controlling terminal, the process is ignoring or blocking the SIGTTIN betoken, or the process grouping is orphaned. This fault may also be generated for implementation-divers reasons.
[EISDIR]
[XSI] [Option Start] The fildes argument refers to a directory and the implementation does not allow the directory to exist read using read() or pread(). The readdir() role 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 offset maximum established in the open up 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 not connected.
[ETIMEDOUT]
A read was attempted on a socket and a manual timeout occurred.

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

[EIO]
A physical I/O error has occurred.
[ENOBUFS]
Insufficient resource were available in the arrangement to perform the operation.
[ENOMEM]
Insufficient retention 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 argument is invalid. The value is negative. [Option End]
[EOVERFLOW]
[XSI] [Option Start] The file is a regular file and an attempt was made to read at or beyond the offset maximum associated with the file. [Option End]
[ENXIO]
[XSI] [Option Start] A asking 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 past 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.ane-2001 does not specify the value of the file start after 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 every bit [EAGAIN], conspicuously the pointer should not change. Later an interrupt or hardware error, notwithstanding, an updated value would be very useful and is the behavior of many implementations.

Note that a read() of goose egg bytes does not modify st_atime. A read() that requests more than aught bytes, simply returns cypher, shall change st_atime.

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

Input and Output

The use of I/O with big byte counts has e'er presented problems. Ideas such every bit lread() and lwrite() (using and returning longs) were considered at one time. The electric current solution is to use abstract types on the ISO C standard office to read() and write(). The abstruse types tin be declared so that existing functions work, but can also exist declared and then that larger types can be represented in hereafter implementations. It is presumed that whatsoever 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 limited and then that a signed render value remains meaningful. Since the render type is also a (signed) abstruse blazon, the byte count tin can exist divers past the implementation to be larger than an int tin hold.

The standard developers considered adding 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 be an aid to applications portability.

This volume of IEEE Std 1003.1-2001 requires that no activeness be taken for read() or write() when nbyte is zero. This is not intended to take precedence over detection of errors (such every bit invalid buffer pointers or file descriptors). This is consistent with the balance of this volume of IEEE Std 1003.i-2001, but the phrasing here could exist misread to crave detection of the zero instance earlier any other errors. A value of zero is to be considered a right value, for which the semantics are a no-op.

I/O is intended to exist diminutive 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. Information technology is a known aspect of terminals that this is not honored, and terminals are explicitly (and implicitly permanently) excepted, making the behavior unspecified. The behavior for other device types is also left unspecified, but the wording is intended to imply that futurity standards might choose to specify atomicity (or non).

There were recommendations to add format parameters to read() and write() in order to handle networked transfers among heterogeneous file arrangement and base hardware types. Such a facility may exist required for support past the OSI presentation of layer services. However, it was determined that this should represent with similar C-language facilities, and that is beyond the scope of this book of IEEE Std 1003.one-2001. The concept was suggested to the developers of the ISO C standard for their consideration equally a possible expanse for future piece of work.

In four.3 BSD, a read() or write() that is interrupted past a bespeak before transferring whatever data does not past default return an [EINTR] fault, but is restarted. In 4.two BSD, four.3 BSD, and the 8th Edition, there is an additional function, select(), whose purpose is to intermission until specified activeness (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 as keyboard input) where pause of I/O due to a signal is desired.

The issue of which files or file types are interruptible is considered an implementation pattern issue. This is often afflicted primarily by hardware and reliability bug.

There are no references to actions taken following an "unrecoverable error". Information technology is considered beyond the scope of this volume of IEEE Std 1003.1-2001 to describe what happens in the example of hardware errors.

Previous versions of IEEE Std 1003.one-2001 allowed two very different behaviors with regard to the handling of interrupts. In society to minimize the resulting defoliation, it was decided that IEEE Std 1003.ane-2001 should support only one of these behaviors. Historical practice on AT&T-derived systems was to accept read() and write() return -one and set up errno to [EINTR] when interrupted after some, only not all, of the data requested had been transferred. However, the U.Due south. Section of Commerce FIPS 151-1 and FIPS 151-2 require the historical BSD beliefs, in which read() and write() return the number of bytes really transferred before the interrupt. If -1 is returned when whatsoever data is transferred, it is hard to recover from the fault on a seekable device and impossible on a non-seekable device. Well-nigh new implementations support this beliefs. The behavior required by IEEE Std 1003.1-2001 is to return the number of bytes transferred.

IEEE Std 1003.1-2001 does not specify when an implementation that buffers read()s actually moves the data into the user-supplied buffer, so an implementation may choose to do this at the latest possible moment. Therefore, an interrupt arriving earlier may not crusade read() to return a partial byte count, but rather to return -1 and gear up errno to [EINTR].

Consideration was also given to combining the two previous options, and setting errno to [EINTR] while returning a short count. Even so, not simply is at that place no existing practice that implements this, information technology is also contradictory to the idea that when errno is prepare, the function responsible shall return -1.

FUTURE DIRECTIONS

None.

Come across ALSO

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

CHANGE HISTORY

First released in Issue 1. Derived from Issue i of the SVID.

Issue 5

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

Large File Meridian extensions are added.

The pread() function is added.

Consequence 6

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

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

  • The DESCRIPTION now states that if read() is interrupted by a signal afterwards information technology has successfully read some data, it returns the number of bytes read. In Issue 3, information technology was optional whether read() returned the number of bytes read, or whether it returned -i with errno ready 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 outset maximum established in the open file description associated with fildes. This change is to support big files.

  • The [EOVERFLOW] mandatory error condition is added.

  • The [ENXIO] optional mistake condition is added.

Text referring to sockets is added to the Description.

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

  • The effect of reading zero 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 weather are added for operations on sockets: [EAGAIN], [ECONNRESET], [ENOTCONN], and [ETIMEDOUT].

The [EIO] fault is made optional.

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

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

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

IEEE Std 1003.one-2001/Cor two-2004, item XSH/TC2/D6/109 is applied, making an editorial correction in the RATIONALE section.

Finish of informative text.


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

kochdestoo1958.blogspot.com

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

0 Response to "Coninue Read a File in a Function"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel