2.1.10.58 WriteFile


Description

This function writes data to a file. WriteFile starts writing data to the file at the position indicated by the file pointer. After the write operation has been completed, the file pointer is adjusted by the number of bytes actually written.

Syntax

BOOL WriteFile( HANDLE hFile, LPVOID lpBuffer, DWORD nNumberOfBytesToWrite, DWORD * lpNumberOfBytesWritten, OVERLAPPED * lpOverlapped = NULL )

Parameters

hFile
[input] Handle to the file to be written to. The file handle must have been created with GENERIC_WRITE access to the file.
lpBuffer
[input] Pointer to the buffer containing the data to be written to the file.
nNumberOfBytesToWrite
[input] Number of bytes to write to the file. A value of zero specifies a null write operation.
A null write operation does not write any bytes but does cause the time stamp to change.
lpNumberOfBytesWritten
[output] Pointer to the number of bytes written by this function call. WriteFile sets this value to zero before doing any work or error checking.
lpOverlapped
[input] Unsupported; set to NULL.

Return

Nonzero indicates success. Zero indicates failure.

Examples

EX1

int WriteFile_ex1()
{
    string strNewFilePath = "c:\\temp.txt";
    ///Create new file or open an exist file.
    HANDLE hFile;
    DWORD        dwBytesWritten;

    hFile = CreateFile( strNewFilePath,
                        GENERIC_WRITE,
                        FILE_SHARE_READ,
                        NULL,
                        CREATE_NEW | OPEN_EXISTING,
                        FILE_ATTRIBUTE_NORMAL,
                        NULL);
    if (hFile == INVALID_HANDLE_VALUE) 
    { 
        out_str("Could not Create file.");   // process error
        return -1;
    } 
    
    string strWrite = "Hello World";
    LPCSTR lpcszWrite = (LPCSTR)strWrite;
    bool bRet = WriteFile( hFile, &lpcszWrite, strWrite.GetLength(), &dwBytesWritten,NULL);

    // codes to read the file
    CloseHandle(hFile);// must close file after reading
    
    return 1;            
}

Remark

See Also

CreateFile

Header to Include

origin.h

Reference