Writes data to a file.
#include <io.h> | Required only for function declarations |
int _write( int handle, void *buffer, unsigned int count );
buffer | Data to be written | |
count | Number of bytes |
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.
The _write function returns the number of bytes actually written. The return value may be positive but less than count (for example, when _write runs out of disk space before count bytes are written).
A return value of –1 indicates an error. In this case, errno is set to one of the following values:
Value | Meaning |
EBADF | Invalid file handle or file not opened for writing |
ENOSPC | No space left on device |
For 16-bit platforms, if you are writing more than 32K (the maximum size for type int) to a file, the return value should be of type unsigned int. (See the example that follows.) However, the maximum number of bytes that can be written to a file at one time is 65,534, since 65,535 (or OxFFFF) is indistinguishable from –1 and would return an error.
If the file is opened in text mode, each line-feed character is replaced with a carriage-return–line-feed pair in the output. The replacement does not affect the return value.
When writing to files opened in text mode, the _write function 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.
Standards:UNIX
16-Bit:DOS, QWIN, WIN, WIN DLL
32-Bit:DOS32X
Use _write for compatibility with ANSI naming conventions of non-ANSI functions. Use write and link with OLDNAMES.LIB for UNIX compatibility.
/* 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 );
}
}
Wrote 35 bytes to file