Read First 2 Bytes of File C++

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

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


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

DESCRIPTION

The read() function shall try 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.

Before whatever action described below is taken, and if nbyte is zilch, the read() role may observe and return errors as described below. In the absence of errors, or if error detection is not performed, the read() function shall render nix and accept no other results.

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

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

No information transfer shall occur by the current end-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 outcome of subsequent read() requests is implementation-divers.

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 pipe open for writing, read() shall render 0 to bespeak end-of-file.

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

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

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

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

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

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

The read() office reads data previously written to a file. If any portion of a regular file prior to the cease-of-file has not been written, read() shall render bytes with value 0. For example, lseek() allows the file offset to exist prepare beyond the finish of existing information in the file. If data is afterward written at this point, subsequent reads in the gap between the previous end of data and the newly written data shall render 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 render the number of bytes read. This number shall never exist greater than nbyte. The value returned may exist less than nbyte if the number of bytes left in the file is less than nbyte, if the read() request was interrupted past a signal, or if the file is a pipage 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 i typed line of data.

If a read() is interrupted by a indicate earlier it reads any data, it shall render -ane with errno set to [EINTR].

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

For regular files, no information transfer shall occur past 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 $.25 have been set, 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 complete as divers by synchronized I/O file integrity completion. [Option End]

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

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

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

In STREAMS message-nondiscard mode, read() shall retrieve data until every bit many bytes as were requested are transferred, or until a message boundary is reached. If read() does non remember all the data in a message, the remaining information shall be left on the STREAM, and can be retrieved by the next read() call. Message-discard style also retrieves data until as many bytes equally were requested are transferred, or a message purlieus is reached. Still, 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 cipher-byte STREAMS messages is determined past the current read mode setting. In byte-stream mode, read() shall take data until it has read nbyte bytes, or until in that location is no more data to read, or until a zero-byte message block is encountered. The read() office shall so return the number of bytes read, and place the zero-byte message back on the STREAM to be retrieved by the next read(), getmsg(), or getpmsg(). In message-nondiscard way or message-discard mode, a zero-byte message shall render 0 and the message shall be removed from the STREAM. When a zero-byte bulletin is read as the showtime bulletin on a STREAM, the message shall be removed from the STREAM and 0 shall exist returned, regardless of the read style.

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

By default, STREAMs are in control-normal style, in which a read() from a STREAMS file can merely process messages that contain a data part merely do not contain a control function. The read() shall fail if a message containing a control office is encountered at the STREAM caput. This default action 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 whatever control part to data and pass information technology to the application before passing any data part originally nowadays in the aforementioned message. In control-discard style, read() shall discard bulletin control parts but render to the process whatever data part in the message.

In improver, read() shall neglect if the STREAM head had processed an asynchronous error before the call. In this case, the value of errno shall non reflect the consequence of read(), but reflect the prior error. If a hangup occurs on the STREAM existence read, read() shall go on to operate normally until the STREAM head read queue is empty. Thereafter, it shall render 0. [Option End]

[XSI] [Option Start] The pread() function shall be equivalent to read(), except that information technology shall read from a given position in the file without changing the file pointer. The first iii arguments to pread() are the aforementioned as read() with the addition of a 4th argument starting time 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 return a non-negative integer indicating the number of bytes actually read. Otherwise, the functions shall render -i and set errno to betoken the error.

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 non a valid file descriptor open for reading.
[EBADMSG]
[XSR] [Option Start] The file is a STREAM file that is prepare to control-normal style and the message waiting to be read includes a control part. [Option End]
[EINTR]
The read operation was terminated due to the receipt of a signal, and no data was transferred.
[EINVAL]
[XSR] [Option Start] The STREAM or multiplexer referenced past fildes is linked (direct 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 mistake may also be generated for implementation-divers reasons.
[EISDIR]
[XSI] [Option Start] The fildes statement refers to a directory and the implementation does not allow the directory to be read using read() or pread(). The readdir() function should be used instead. [Option End]
[EOVERFLOW]
The file is a regular file, nbyte is greater than 0, the starting position is before the finish-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 neglect 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 non 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 physical I/O mistake has occurred.
[ENOBUFS]
Insufficient resources were available in the system to perform the operation.
[ENOMEM]
Insufficient memory was available 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() role shall fail, and the file pointer shall remain unchanged, if:

[EINVAL]
[XSI] [Option Start] The showtime 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 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 post-obit 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[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 non specify the value of the file kickoff afterwards an fault 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 as [EAGAIN], conspicuously the arrow should non change. Afterwards an interrupt or hardware fault, however, an updated value would exist very useful and is the beliefs of many implementations.

Annotation that a read() of zero bytes does non modify st_atime. A read() that requests more zero bytes, but returns zero, shall change st_atime.

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

Input and Output

The utilise of I/O with large byte counts has always presented problems. Ideas such every bit lread() and lwrite() (using and returning longs) were considered at i fourth dimension. The current solution is to apply abstract types on the ISO C standard function to read() and write(). The abstruse types can exist alleged so that existing functions work, but can also be declared so that larger types can exist represented in futurity implementations. It is presumed that whatsoever constraints limit the maximum range of size_t also limit portable I/O requests to the aforementioned range. This volume of IEEE Std 1003.1-2001 as well limits the range further past requiring that the byte count be limited and so that a signed return value remains meaningful. Since the return type is besides a (signed) abstract type, the byte count can be defined by the implementation to be larger than an int can concur.

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 any other size that would be an aid to applications portability.

This volume of IEEE Std 1003.ane-2001 requires that no activeness be taken for read() or write() when nbyte is nada. 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 rest of this book of IEEE Std 1003.1-2001, but the phrasing hither could be misread to require detection of the null case before whatever other errors. A value of nil is to be considered a correct value, for which the semantics are a no-op.

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

There were recommendations to add together format parameters to read() and write() in order to handle networked transfers amidst heterogeneous file system and base hardware types. Such a facility may exist required for support past the OSI presentation of layer services. Nevertheless, it was adamant that this should correspond with similar C-language facilities, and that is beyond the scope of this volume of IEEE Std 1003.i-2001. The concept was suggested to the developers of the ISO C standard for their consideration as a possible surface area for hereafter piece of work.

In four.3 BSD, a read() or write() that is interrupted past a bespeak before transferring any data does not by default return an [EINTR] error, but is restarted. In 4.two BSD, iv.3 BSD, and the Eighth Edition, there is an additional role, select(), whose purpose is to pause until specified activity (data to read, space to write, and 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 intermission of I/O due to a signal is desired.

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

There are no references to actions taken following an "unrecoverable error". It is considered beyond the scope of this volume of IEEE Std 1003.i-2001 to depict what happens in the example of hardware errors.

Previous versions of IEEE Std 1003.i-2001 allowed ii very dissimilar 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 ane of these behaviors. Historical exercise on AT&T-derived systems was to have read() and write() return -one and gear up errno to [EINTR] when interrupted later some, but not all, of the data requested had been transferred. Withal, the U.S. Department of Commerce FIPS 151-1 and FIPS 151-ii crave the historical BSD behavior, in which read() and write() return the number of bytes really transferred before the interrupt. If -1 is returned when whatever data is transferred, information technology is difficult to recover from the mistake on a seekable device and impossible on a non-seekable device. Near new implementations support this behavior. The behavior required by IEEE Std 1003.1-2001 is to render the number of bytes transferred.

IEEE Std 1003.ane-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 cause read() to return a fractional byte count, but rather to render -one and set errno to [EINTR].

Consideration was also given to combining the ii 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 gear up, the function responsible shall return -1.

Time to come DIRECTIONS

None.

SEE ALSO

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

Alter HISTORY

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

Consequence five

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

Large File Meridian extensions are added.

The pread() role is added.

Event half-dozen

The DESCRIPTION and ERRORS sections are updated and 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 now states that if read() is interrupted by a indicate after 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 ready 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 offset maximum established in the open up file clarification associated with fildes. This modify is to support large files.

  • The [EOVERFLOW] mandatory fault status 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 draft 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 retentivity objects.

New RATIONALE is added to explicate 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] error is made optional.

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

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

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

IEEE Std 1003.ane-2001/Cor 2-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 Group.
POSIX ® is a registered Trademark of The IEEE.
[ Main Index | XBD | XCU | XSH | XRAT ]

gardnerquer1990.blogspot.com

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

0 Response to "Read First 2 Bytes of File C++"

إرسال تعليق

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel