Name
read - Reads from a file.
Syntax
#include <io.h>
int read(handle, buffer, count)
int handle;
char *buffer;
unsigned int count;
Description
The read function attempts to read count bytes into buffer
from the file associated with handle. The read operation
begins at the file pointer's current position associated
with the given file. After the read operation, the file
pointer points to the next unread character.
Return Value
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 the
file is locked (DOS and OS/2 Versions
3.0 and later only).
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 is
65,534 at a time, since 65,535 (or 0xFFFF) is
indistinguishable from -1, and therefore would look like 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 under DOS and OS/2, 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 file must
be closed to clear the end-of-file indicator.
See Also
creat(DOS), fread(DOS), open(DOS), write(DOS)
Example
#include <fcntl.h> /* Needed only for **
** O_RDWR definition */ #include <io.h>
#include <stdio.h> char buffer[60000];
main()
{
int fh;
unsigned int nbytes = 60000, bytesread;
/* Open file for input: */
if ((fh = open("data",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);
}
This program opens a file named data and tries to read
60,000 bytes from that file using read. It then displays the
actual number of bytes read from data.
(printed 6/18/89)