Reads bytes from a file and places them in a buffer.
Format
#include <unistd.h>
ssize_t read (int file_desc, void *buffer, size_t nbytes);
(ISO POSIX-1)
int read (int file_desc, void *buffer, int nbytes);
(Compatibility)
1 – Arguments
file_desc
A file descriptor. The specified file descriptor must refer to a
file currently opened for reading.
buffer
The address of contiguous storage in which the input data is
placed.
nbytes
The maximum number of bytes involved in the read operation.
2 – Description
The read function returns the number of bytes read. The return
value does not necessarily equal nbytes. For example, if the
input is from a terminal, at most one line of characters is read.
NOTE
The read function does not span record boundaries in a
record file and, therefore, reads at most one record. A
separate read must be done for each record.
3 – Return Values
n The number of bytes read.
-1 Indicates a read error, including physical
input errors, illegal buffer addresses,
protection violations, undefined file
descriptors, and so forth.
4 – Example
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
main()
{
int fd,
i;
char buf[10];
FILE *fp ; /* Temporary STDIO file */
/* Create a dummy data file */
if ((fp = fopen("test.txt", "w+")) == NULL) {
perror("open");
exit(1);
}
fputs("XYZ\n",fp) ;
fclose(fp) ;
/* And now practice "read" */
if ((fd = open("test.txt", O_RDWR, 0, "shr=upd")) <= 0) {
perror("open");
exit(0);
}
/* Read 2 characters into buf. */
if ((i = read(fd, buf, 2)) < 0) {
perror("read");
exit(0);
}
/* Print out what was read. */
if (i > 0)
printf("buf='%c%c'\n", buf[0], buf[1]);
close(fd);
}