WriteFile返回无效句柄

时间:2016-10-14 10:34:08

标签: c++ windows file winapi io

我正在尝试使用Windows WriteFile API,如下所示:

class FileWriter
{
public:
    FileWriter(const std::string & path);
    ~FileWriter();
    bool write(unsigned char * buffer, int num_bytes, unsigned __int64 offset);

private:
    HANDLE                  file_h;
};

实施很简单:

FileWriter::FileWriter(const std::string & path)
{
    file_h = CreateFileA(path.c_str(), GENERIC_WRITE, 
        FILE_SHARE_READ, 0, CREATE_ALWAYS, 
        FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, 0);

    if (file_h == INVALID_HANDLE_VALUE) {
        throw std::runtime_error("Could not open the output file");
    }
}

FileWriter::~FileWriter()
{
    if (file_h != INVALID_HANDLE_VALUE) {
        CloseHandle(file_h);
    }
}

bool FileWriter::write(unsigned char * buffer, int num_bytes,
    unsigned __int64 offset)
{
    if (file_h != INVALID_HANDLE_VALUE && buffer) {
        OVERLAPPED overlapped;
        overlapped.Offset = offset & 0xFFFFFFFF;
        overlapped.OffsetHigh = offset >> 32;

        BOOL e = WriteFile(file_h, buffer, num_bytes, 
            0, &overlapped);
        DWORD c = GetLastError();

        LPSTR messageBuffer = nullptr;
        size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
            NULL, c, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&messageBuffer, 0, NULL);

        std::string message(messageBuffer, size);

        //Free the buffer.
        LocalFree(messageBuffer);

        if (e == FALSE && c == ERROR_IO_PENDING) {
            return true;
        }
        else {
            if ((e == TRUE) && (c == ERROR_SUCCESS))
                return true;
        }
    }
    return false;
}

这总是因The handle is invalid错误而失败。但是,文件句柄始终有效。我甚至检查它。所以,我不确定我做错了什么。

0 个答案:

没有答案