C/C++ Windows API——文件读写

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

#include "stdafx.h"
#include 
#include 

int main()
{
    //没有设置这句的话,printf中出现汉字包含后面的非汉字全部都打不出来
    setlocale(LC_ALL, "chs");

    BOOL ret;
    LPCWSTR filePath = _T("C:\\Users\\Administrator\\Desktop\\file_demo_test.txt");

    DWORD dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
    DWORD dwShareMode = 0;
    LPSECURITY_ATTRIBUTES lpSecurityAttributes = NULL;
    DWORD dwCreationDisposition = OPEN_ALWAYS;
    DWORD dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
    HANDLE hTemplateFile = NULL;
    HANDLE handle = CreateFile(filePath, dwDesiredAccess, dwShareMode, lpSecurityAttributes, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile);
    if (handle == NULL) {
        printf("CreateFile fail(%ld)", GetLastError());
    }
    else {
        DWORD len;
        TCHAR *writeBuf = L"Win32 API 你好";
        TCHAR readBuf[1024];

        /*
        ASCII:不加前缀(如果写入unicode字符串读出来会是乱码)
        Unicode:0xFEFF
        UTF8:0xEFBBBF
        注意写入后用十六进制编辑器查看高低位是互换的(因为C是小端编码)
        */
        WORD prefix = 0xFEFF;

        /*
        BOOL WriteFile(
        HANDLE  hFile,//文件句柄
        LPCVOID lpBuffer,//数据缓存区指针
        DWORD   nNumberOfBytesToWrite,//你要写的字节数
        LPDWORD lpNumberOfBytesWritten,//用于保存实际写入字节数的存储区域的指针
        LPOVERLAPPED lpOverlapped//OVERLAPPED结构体指针
        );
        return 失败返回0,成功返回非0
        */
        ret = WriteFile(handle, &prefix, 2, &len, NULL);
        if (ret == 0) {
            printf("WriteFile prefix fail(%ld)\n", GetLastError());
        }
        else {
            printf("WriteFile prefix -> writeLen=%d\n", len);
        }

        /*
        把写缓冲区中的数据实际写入到文件中
        WINBASEAPI BOOL WINAPI FlushFileBuffers(_In_ HANDLE hFile);
        return 失败返回0, 成功返回非0
        */
        ret = FlushFileBuffers(handle);
        if (ret == 0) {
            printf("FlushFileBuffers fail(%d)\n", GetLastError());
        }
        else {
            printf("FlushFileBuffers -> ret=%d\n", ret);
        }

        ret = WriteFile(handle, writeBuf, lstrlen(writeBuf)*sizeof(TCHAR), &len, NULL);
        if (ret == 0) {
            printf("WriteFile buf fail(%ld)\n", GetLastError());
        }
        else {
            printf("WriteFile buf=%ls -> writeLen=%ld\r\n", writeBuf, len);
        }

        /*
        一个文件中设置当前的读取位置
        DWORD SetFilePointer(
            HANDLE hFile,               // 文件句柄
            LONG lDistanceToMove,       // 偏移量(低位)
            PLONG lpDistanceToMoveHigh, // 偏移量(高位)
            DWORD dwMoveMethod          // 基准位置FILE_BEGIN:文件开始位置 FILE_CURRENT:文件当前位置 FILE_END:文件结束位置
        );
        return Long,返回一个新位置,它采用从文件起始处开始算起的一个字节偏移量。HFILE_ERROR意味着出错。会设置GetLastError
        */
        DWORD pos = SetFilePointer(handle, 2, 0, FILE_BEGIN);
        if (pos == HFILE_ERROR) {
            printf("SetFilePointer fail(%ld)\n", GetLastError());
        }
        else {
            printf("SetFilePointer -> pos=%ld\n", pos);
        }

        /*
        BOOL ReadFile(
        HANDLE  hFile,                  //文件的句柄
        LPVOID  lpBuffer,               //用于保存读入数据的一个缓冲区
        DWORD   nNumberOfBytesToRead,   //要读入的字节数
        LPDWORD lpNumberOfBytesRead,    //指向实际读取字节数的指针
        LPOVERLAPPED lpOverlapped       //如文件打开时指定了FILE_FLAG_OVERLAPPED,那么必须,用这个参数引用一个特殊的结构。该结构定义了一次异步读取操作。否则,应将这个参数设为NULL
        );
        return 失败返回0,成功返回非0

        注意:ReadFile可以读取文件中所有的数据。如果指针设为FILE_BEGIN的话,有可能读的前几个字节是文件编码,而不是所需的数据,这点要小心
        */
        ret = ReadFile(handle, readBuf, 1024, &len, NULL);
        if (ret == 0) {
            printf("ReadFile fail(%ld)\n", GetLastError());
        }
        else {
            //凡是从文件流中读出来的字符串都不会自动补\0,需要手动填充
            readBuf[len / sizeof(TCHAR)] = L'\0';
            printf("ReadFile -> len=%ld, buf=%ls\n", len, readBuf);
        }

        CloseHandle(handle);
    }

    system("pause");
    return 0;
}

C/C++ Windows API——文件读写_第1张图片

你可能感兴趣的:(——,Windows,API)