Updated: October 28, 2024 |
Read bytes from a file
#include <unistd.h> ssize_t read( int filedes, void* buf, size_t nbytes );
libc
Use the -l c option to qcc to link against this library. This library is usually included automatically.
The read() function attempts to read nbytes bytes from the file associated with the open file descriptor, filedes, into the buffer pointed to by buf.
On a regular file or other file capable of seeking, read() starts at a position in the file given by the file offset associated with filedes. Before successfully returning from read(), the file offset is incremented by the number of bytes actually read.
On a file not capable of seeking, read() starts at the current position.
When read() returns successfully, its return value is the number of bytes actually read and placed in the buffer. POSIX requires that this number never be greater than nbytes, but that depends on the underlying resource manager. The number may be less than nbytes if, for example:
If read() is interrupted by a signal before it reads any data, it returns -1 and sets errno to EINTR. However, if read() is interrupted by a signal after it has successfully read some data, it returns the number of bytes read.
No data is transferred past the current end of file. If the starting position is at or after the end of file, read() returns zero. If the file is a device special file, the result of subsequent calls to read() will work, based on the then-current state of the device (that is, the end of file is transitory).
When attempting to read from an empty pipe or FIFO:
When attempting to read from a file (other than a pipe or FIFO) that supports nonblocking reads and has no data currently available:
If you call read() on a portion of a file, prior to the end of file, that hasn't been written, it stores bytes with the value zero in buffer.
If read() succeeds, the st_atime field of the file is marked for update.
The number of bytes actually read, or -1 (errno is set).
#include <sys/types.h> #include <fcntl.h> #include <unistd.h> #include <stdlib.h> #include <stdio.h> int main( void ) { int fd; int size_read; char buffer[80]; /* Open a file for input */ fd = open( "myfile.dat", O_RDONLY ); /* Read the text */ size_read = read( fd, buffer, sizeof( buffer ) ); /* Test for error */ if( size_read == -1 ) { perror( "Error reading myfile.dat" ); return EXIT_FAILURE; } /* Close the file */ close( fd ); return EXIT_SUCCESS; }
Safety: | |
---|---|
Cancellation point | Yes |
Interrupt handler | No |
Signal handler | Yes |
Thread | Yes |