c - ReadFile 函数返回 ERROR_INVALID_PARAMETER

标签 c winapi readfile

我正在尝试使用 ReadFile 函数。这是我的代码:

#define BUFFERSIZE 5

int main(int argc, char* argv[])
{
    OVERLAPPED overlapIn = {};
    HANDLE tHandle;
    char buf[BUFFERSIZE] = {};
    DWORD  lpNumberOfBytesRead;

    tHandle = CreateFile(
        L"\\\\.\\D:",
        GENERIC_READ,
        FILE_SHARE_READ,
        NULL,
        OPEN_EXISTING,
        FILE_ATTRIBUTE_NORMAL,
        NULL);

    if (tHandle == INVALID_HANDLE_VALUE)
    {
        DWORD error = GetLastError();
        assert(0);
    }

    if (ReadFile(tHandle, &buf, BUFFERSIZE - 1, &lpNumberOfBytesRead, NULL) == 0)
    {
        int error = GetLastError();
        printf("Terminal failure: Unable to read from disk.\n GetLastError=%d\n", error);
        CloseHandle(tHandle);
        return 1;
    }

GetLastError 函数返回代码 87,即 ERROR_INVALID_PARAMETER。

很明显,其中一个参数是错误的,但我不知道是哪个参数,因为我尝试按照文档中所写的方式执行所有操作。

最佳答案

这在 documentation for CreateFile 中有描述:

Volume handles can be opened as noncached at the discretion of the particular file system, even when the noncached option is not specified in CreateFile. You should assume that all Microsoft file systems open volume handles as noncached.

MSDN article on File Buffering描述了非缓存句柄的要求:

File access sizes, including the optional file offset in the OVERLAPPED structure, if specified, must be for a number of bytes that is an integer multiple of the volume sector size. For example, if the sector size is 512 bytes, an application can request reads and writes of 512, 1,024, 1,536, or 2,048 bytes, but not of 335, 981, or 7,171 bytes.

File access buffer addresses for read and write operations should be physical sector-aligned, which means aligned on addresses in memory that are integer multiples of the volume's physical sector size. Depending on the disk, this requirement may not be enforced.

严格的代码应该检查有问题的文件系统的扇区大小,然后使用 this approach分配内存。但是,根据我的经验,扇区大小始终小于或等于分配粒度,因此您可以只使用 VirtualAlloc() 就可以了。分配内存块。

关于c - ReadFile 函数返回 ERROR_INVALID_PARAMETER,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31697229/

相关文章:

c# - 读取文件时引发事件?

c++ - 在图片控件中使用 SS_REALSIZECONTROL 时出现语法错误

C++从文件中读取并标记数据

c - Linux系统V IPC : Unable to initialize semaphore value

c - C 中文本文件的奇怪错误

c - '<<' 在 C 中是什么意思?

java - 如何从文件中读取html?

c - 为什么 Gwan 缓存我的结果,我可以禁用它吗?

c# - 如何以编程方式安装字体

android - 如何从android中的手机内存中读取文件?