RAD Studio
ContentsIndex
PreviousUpNext
read

Header File 

io.h  

Category 

Input/output Routines 

Prototype 

int read(int handle, void *buf, unsigned len); 

Description 

Reads from file. 

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. 

The file handle handle is 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 UINT_MAX -1, because UINT_MAX is the same as -1, the error return indicator. UINT_MAX is defined in limits.h. 

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 values:

EACCES 
Permission denied 
EBADF 
Bad file number 

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(10);
/* 
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.$$$", O_RDONLY | O_BINARY, S_IWRITE | S_IREAD)) == -1)
   {
      printf("Error Opening File\n");
      exit(1);
   }
   if ((bytes = read(handle, buf, 10)) == -1) {
      printf("Read Failed.\n");
      exit(1);
   }
   else {
      printf("Read: %d bytes read.\n", bytes);
   }
   return 0;
}

Portability

POSIX 
Win32 
ANSI C 
ANSI C++ 
 
 
Copyright(C) 2008 CodeGear(TM). All Rights Reserved.
What do you think about this topic? Send feedback!