Purpose

The read function is used to read data from a file (identified by a handle), without formatting, type conversion, or buffering.

Header Files

io.h
(read)
errno.h
(errno values)

Prototype

int read (int Handle, void * Buffer, unsigned Length);

Arguments

Handle
Selector (file descriptor) of an open file.
Buffer
The address where the data read is to be stored.
Length
The number of bytes to be read.

Return Value 1

int
Number of bytes read.

Side Effect

errno
Iff the read fails, the global variable errno is set to one of:
EBADF
Handle not open

Example

#include <stdio.h>
#include <io.h> 
#include <fcntl.h>
#include <errno.h>

int main () {
  int Account_Master;
  char Buffer [100]; 
  int Maximum; 
  int Actual;
  /* Other declarations */
  Maximum = 100;
  Account_Master = open ("accounts.dat", O_RDONLY);
  if (Account_Master >0) {
    printf ("Open succeeded.\n");
  } else {
    printf ("Open failed.\n")
    switch (errno) {
      case EACCES:  printf ("Permission denied.\n"); break;
      case EINVACC: printf ("Invalid access mode.\n"); break;
      case EMFILE:  printf ("No file handle available.\n"); break;
      case ENOENT:  printf ("File or path not found.\n"); break;
      default:      printf ("Unknown error.\n"); break;
    }
  /* File processing */
  Actual = 1;
  while (Actual > 0)
    Actual = read (Account_Master, Buffer, Maximum); 
    if (Actual < Maximum) { 
      printf ("An incomplete record was read.\n")
    }
    /* Record processing */
  }
  
  if (close (Account_Master) == 0) {
    printf ("Close succeeded.\n");
  } else {
    printf ("Close failed.\n")
    switch (errno) {
      case EBADF:  printf ("File not open.\n"); break;
      default:     printf ("Unknown error.\n"); break;
    }
  }
  return 0;
}

See Also

write   Write a file

Valid HTML 4.01 Transitional

Valid CSS

Site Icon Copyright © 1999-2007, jhyoung, revised 4/30/2007