Reads data from a file.
#include <io.h> | Required only for function declarations |
int _read( int handle, void *buffer, unsigned int count );
handle | Handle referring to open file | |
buffer | Storage location for data | |
count | Maximum number of bytes |
The _read function attempts to read count bytes into buffer from the file associated with handle. The read operation begins at the current position of the file pointer associated with the given file. After the read operation, the file pointer points to the next unread character.
The _read function returns the number of bytes actually read, which may be less than count if there are fewer than count bytes left in the file, or if the file was opened in text mode (see below). The return value 0 indicates an attempt to read at end-of-file. The return value –1 indicates an error, and errno is set to the following value:
Value | Meaning |
EBADF | The given handle is invalid; or the file is not open for reading; or (DOS versions 3.0 and later) the file is locked. |
For 16-bit platforms, if you are reading more than 32K (the maximum size for type int) from a file, the return value should be of type unsigned int (see the example that follows). However, the maximum number of bytes that can be read from a file in one operation is 65,534, since 65,535 (or 0xFFFF) is indistinguishable from –1, and therefore cannot be distinguished from an error return.
If the file was opened in text mode, the return value may not correspond to the number of bytes actually read. When text mode is in effect, each carriage-return–line-feed (CR-LF) pair is replaced with a single line-feed character. Only the single line-feed character is counted in the return value. The replacement does not affect the file pointer.
Note that when files are opened in text mode, a CTRL+Z character is treated as an end-of-file indicator. When the CTRL+Z is encountered, the read terminates, and the next read returns 0 bytes. The _lseek function will clear the end-of-file indicator.
Standards:UNIX
16-Bit:DOS, QWIN, WIN, WIN DLL
32-Bit:DOS32X
Use _read for compatibility with ANSI naming conventions of non-ANSI functions. Use read and link with OLDNAMES.LIB for UNIX compatibility.
/* READ.C: This program opens a file named READ.C and tries to read 60,000
* bytes from that file using read. It then displays the actual
* number of bytes read from READ.C.
*/
#include <fcntl.h> /* Needed only for _O_RDWR definition */
#include <io.h>
#include <stdlib.h>
#include <stdio.h>
char buffer[60000];
void main( void )
{
int fh;
unsigned int nbytes = 60000, bytesread;
/* Open file for input: */
if( (fh = _open( “read.c”, _O_RDONLY )) == -1 )
{
perror( “open failed on input file” );
exit( 1 );
}
/* Read in input: */
if( ( bytesread = _read( fh, buffer, nbytes ) ) <= 0 )
perror( “Problem reading file” );
else
printf( “Read %u bytes from file\n”, bytesread );
_close( fh );
}
Read 747 bytes from file