win32 写一个文件 (同步阻塞写的方式)

参考网页:

https://msdn.microsoft.com/en-us/library/windows/desktop/bb540534(v=vs.85).aspx

创建一个新文件,并且同步写一个字符串到文件中去。

创建一个VS2010 控制台 程序:

// writeFile.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <windows.h>
#include <tchar.h>
#include <stdio.h>
#include <strsafe.h>

void DisplayError(LPTSTR lpszFunction);

#define FILE_NAME   TEXT("126.txt")
void __cdecl _tmain(int argc, TCHAR *argv[])
{
    HANDLE hFile; 
    char DataBuffer[] = "This is some test data to write to the file.";
    DWORD dwBytesToWrite = (DWORD)strlen(DataBuffer);
    DWORD dwBytesWritten = 0;
    BOOL bErrorFlag = FALSE;
    DWORD dw ;

    printf("\n");


    hFile = CreateFile(FILE_NAME,                // name of the write
                       GENERIC_WRITE,          // open for writing
                       0,                      // do not share
                       NULL,                   // default security
                       CREATE_NEW,             // create new file only
                       FILE_ATTRIBUTE_NORMAL,  // normal file
                       NULL);                  // no attr. template

    if (hFile == INVALID_HANDLE_VALUE) 
    { 
         dw = GetLastError();
        _tprintf(TEXT("Terminal failure: Unable to open file \"%s\" for write. Error Code %d\n"), FILE_NAME,dw);
        return;
    }

    _tprintf(TEXT("Writing %d bytes to %s.\n"), dwBytesToWrite, FILE_NAME);

    bErrorFlag = WriteFile( 
                    hFile,           // open file handle
                    DataBuffer,      // start of data to write
                    dwBytesToWrite,  // number of bytes to write
                    &dwBytesWritten, // number of bytes that were written
                    NULL);            // no overlapped structure

    if (FALSE == bErrorFlag)
    {
        dw = GetLastError();
        printf("Terminal failure: Unable to write to file. %d\n",dw);
    }
    else
    {
        if (dwBytesWritten != dwBytesToWrite)
        {
            // This is an error because a synchronous write that results in
            // success (WriteFile returns TRUE) should write all data as
            // requested. This would not necessarily be the case for
            // asynchronous writes.
            printf("Error: dwBytesWritten != dwBytesToWrite\n");
        }
        else
        {
            _tprintf(TEXT("Wrote %d bytes to %s successfully.\n"), dwBytesWritten, FILE_NAME);
        }
    }

    CloseHandle(hFile);
}

运行结果:

Writing 44 bytes to 126.txt.
Wrote 44 bytes to 126.txt successfully.
请按任意键继续. . .

再次运行结果:

Terminal failure: Unable to open file "126.txt" for write. Error Code 80
请按任意键继续. . .

查看文件内容:

This is some test data to write to the file.

猜你喜欢

转载自blog.csdn.net/wowocpp/article/details/80520480