read
Reads from file.
Defined in header <io.h>
Syntax
#include <io.h>
int read(int handle, void *huf, unsigned len);
Portability
| DOS | UNIX | Windows | ANSI C | C++ only |
|---|---|---|---|---|
| ■ | ■ | ■ |
Remarks
read attempts to read len bytes from the file associated with handle into the buffer pointed to by buf.
For a file opened in text mode, read removes carriage returns and reports end-of-file when it reaches a Ctrl-Z.
For _dos_read, handle is a file handle obtained from a creat, open, dup, or dup2 call.
On disk files, read begins reading at the current file pointer. When the reading is complete, it increments the file pointer by the number of bytes read. On devices, the bytes are read directly from the device.
| The maximum | number of bytes that read can read is 65,534, because |
65,535 (0xFFFF) is the same as -1, the error return indicator.
Return value
On successful completion, read returns an integer indicating the number of bytes placed in the buffer. If the file was opened in text mode, read does not count carriage returns or Ctrl-Z characters in the number of bytes read.
On end-of-file, read returns 0. On error, read returns -1 and sets the global variable errno to one of the following:
| EACCES | Permission denied |
| EBADF | Bad file number |
See also
Example
include <stdio.h>
#include <io.h>
#include <alloc.h>
#include <fcntl.h>
#include <process.h>
#include <sys\stat.h>
int main(void)
{
void *buf;
int handle, bytes;
buf = malloc(lO);
/* Looks for a file in the current directory named TEST.$$$ and attempts to
read 10 bytes from it. To use this example you should create the file
TEST.$$$ */
if ((handle = open("TEST.$$$", 0_RDONLY I 0_BINARY,
S_IWRITE I S_IREAD)) == -1) {
printf("Error Opening File\n");
exit(l);
}
if ((bytes = read(handle, buf, 10)) == -1)
printf("Read Failed.\n");
exit(l);
}
else {
printf("Read: %d bytes read.\n", bytes);
}
return 0;
Differences from modern implementations
Nothing recorded yet.
Modern references
These are search links, not yet checked by hand.
Stable link: /3.1/io.h/read/
· short form /3.1/read/