previous | start | next

The Linux I/O read function

The read Function:

      nrd = read(fd, buf, N)
     

At end of file read returns 0.

    1   #include <fcntl.h>  // for open and read
    2   int main()
    3   {
    4     int fd;
    5     
    6     char ch;
    7     size_t nrd;
    8   
    9     fd = open("foo.txt", O_RDONLY);
   10     if ( fd < 0 ) {
   11       printf("Could not open file foo.txt for input.\n");
   12       exit(1);
   13     }
   14   
   15     while( (nrd = read(fd, &ch, 1)) > 0 ) {
   16       printf("%c", ch);
   17     }
   18     return 0;
   19   }


previous | start | next