RAD Studio
ContentsIndex
PreviousUpNext
write

Header File 

io.h 

Category 

Input/output Routines 

Prototype 

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

Description 

Writes to a file. 

write writes a buffer of data to the file or device named by the given handle. handle is a file handle obtained from a creat, open, dup, or dup2 call. 

This function attempts to write len bytes from the buffer pointed to by buf to the file associated with handle. Except when write is used to write to a text file, the number of bytes written to the file will be no more than the number requested. The maximum number of bytes that write can write is UINT_MAX -1, because UINT_MAX is the same as -1, which is the error return indicator for write. On text files, when write sees a linefeed (LF) character, it outputs a CR/LF pair. UINT_MAX is defined in limits.h. 

If the number of bytes actually written is less than that requested, the condition should be considered an error and probably indicates a full disk. For disks or disk files, writing always proceeds from the current file pointer. For devices, bytes are sent directly to the device. For files opened with the O_APPEND option, the file pointer is positioned to EOF by write before writing the data. 

Return Value 

write returns the number of bytes written. A write to a text file does not count generated carriage returns. In case of error, write 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 <stdlib.h>
#include <fcntl.h>
#include <sys\stat.h>
#include <io.h>
#include <string.h>
int main(void)
{
   int handle;
   char string[40];
   int length, res;
/* 
Create a file named "TEST.$$$" in the current directory and write a string to it.  If "TEST.$$$" already exists, it will be overwritten.
 */
   if ((handle = open("TEST.$$$", O_WRONLY | O_CREAT | O_TRUNC,
                         S_IREAD | S_IWRITE)) == -1)
   {
      printf("Error opening file.\n");
      exit(1);
   }
   strcpy(string, "Hello, world!\n");
   length = strlen(string);
   if ((res = write(handle, string, length)) != length)
   {
      printf("Error writing to the file.\n");
      exit(1);
   }
   printf("Wrote %d bytes to the file.\n", res);
   close(handle);
   return 0;
}

Portability

POSIX 
Win32 
ANSI C 
ANSI C++ 
 
 
Copyright(C) 2009 Embarcadero Technologies, Inc. All Rights Reserved.
What do you think about this topic? Send feedback!