Collapse the table of content
Expand the table of content
Important This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here. ArchiveDisclaimer


Writes data to a file.

int _write(
   int fd,
   const void *buffer,
   unsigned int count 


File descriptor of file into which data is written.
Data to be written.
Number of bytes.

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 descriptor 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.

See _doserrno, errno, _sys_errlist, and _sys_nerr for more information on these, and other, return codes.

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.


The _write function writes count bytes from buffer into the file associated with fd. 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.


Routine Required header Compatibility
_write <io.h> Win 98, Win Me, Win NT, Win 2000, Win XP

For additional compatibility information, see Compatibility in the Introduction.


All versions of the C run-time libraries.


This program opens a file for output and uses _write to write some bytes to the file.

// crt_write.c
#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";

int 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" );
         printf( "Wrote %u bytes to file\n", byteswritten );

      _close( fh );


Wrote 36 bytes to file

See Also

Low-Level I/O Routines | fwrite | _open | _read | Run-Time Routines and .NET Framework Equivalents

© 2015 Microsoft