_write

Writes data to a file.

int_write(inthandle**,constvoid*buffer,unsignedintcount);**

Routine Required Header Compatibility
_write <io.h> Win 95, Win NT

For additional compatibility information, see Compatibility in the Introduction.

Libraries

LIBC.LIB Single thread static library, retail version
LIBCMT.LIB Multithread static library, retail version
MSVCRT.LIB Import library for MSVCRT.DLL, retail version

Return Value

If successful, _write returns the number of bytes actually written. If the actual space remaining on the disk is less than the size of the buffer the function is trying to write to the disk, _write fails and does not flush any of the buffer’s contents to the disk. A return value of –1 indicates an error. In this case, errno is set to one of two values: EBADF, which means the file handle is invalid or the file is not opened for writing, or ENOSPC, which means there is not enough space left on the device for the operation.

If the file is opened in text mode, each linefeed character is replaced with a carriage return – linefeed pair in the output. The replacement does not affect the return value.

Parameters

handle

Handle of file into which data is written

buffer

Data to be written

count

Number of bytes

Remarks

The _write function writes count bytes from buffer into the file associated with handle. The write operation begins at the current position of the file pointer (if any) associated with the given file. If the file is open for appending, the operation begins at the current end of the file. After the write operation, the file pointer is increased by the number of bytes actually written.

When writing to files opened in text mode, _write treats a CTRL+Z character as the logical end-of-file. When writing to a device, _write treats a CTRL+Z character in the buffer as an output terminator.

Example

/* WRITE.C: This program opens a file for output
 * and uses _write to write some bytes to the file.
 */

#include <io.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>

char buffer[] = "This is a test of '_write' function";

void main( void )
{
   int fh;
   unsigned byteswritten;

   if( (fh = _open( "write.o", _O_RDWR | _O_CREAT,
                               _S_IREAD | _S_IWRITE )) != -1 )
   {
      if(( byteswritten = _write( fh, buffer, sizeof( buffer ))) == -1 )
         perror( "Write failed" );
      else
         printf( "Wrote %u bytes to file\n", byteswritten );

      _close( fh );
   }
}

Output

Wrote 36 bytes to file

Low-level I/O Routines

See Also   fwrite, _open, _read