read

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); (Compatability)

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.

Description

This 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.

Return Values
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. 

Example

    #include <file.h>
    #include <unistd.h>
    
    main()
    {
    int fd,i;
    char buf[10];
    
         if ( (fd=open("test.txt",O_RDWR,0,"shr=upd")) <= 0 )
    
         {
              perror("open");
              exit();
         }
    
         /* Read 2 characters into buf.  */
    
         if ( (i=read(fd, buf, 2)) < 0)
    
         {
              perror("read");
              exit();
         }
    
         /* Print out what was read.  */
    
         if( i > 0)
              printf("buf='%c%c'\n",buf[0],buf[1]);
    
          close(fd);
    }
    


Previous Page | Next Page | Table of Contents | Index