Purpose

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

Header Files

io.h
(write)
errno.h
(errno values)

Prototype

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

Arguments

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

Return Value 1

int
Number of bytes written.

Side Effect

errno
Iff the write 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;
  int More;
  /* Other declarations */
  Maximum = 100;
  Account_Master = open ("accounts.dat", O_WRONLY);
  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 */
  More = 1;
  while (More == 1)
    /* Record preparation */
    Actual = write (Account_Master, Buffer, Maximum); 
    if (Actual < Maximum) { 
      printf ("An incomplete record was written.\n")
    }
  }
  
  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

read   Read a file

Valid HTML 4.01 Transitional

Valid CSS

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