ReadFile lpBuffer parameter

ReadFile lpBuffer parameter

本文关键字:parameter lpBuffer ReadFile      更新时间:2023-10-16

我正在使用ReadFile读取一个简单字符串,该字符串是我使用WriteFile写入文件的。

有一个简单的字符串:"测试字符串,测试窗口函数"。

使用WriteFile将其写入文件。

现在我想使用ReadFile来确认它是否已写入该文件。我需要将我读到的内容与上面的原始字符串进行比较。要从文件中读取,我有

DWORD dwBytesRead;
char buff[128];
if(!ReadFile(hFile, buff, 128, &dwBytesRead, NULL))
    //Fail

函数返回true,因此它正在从文件中读取。问题是buff充满了正义感。我以前从未遇到过LPVOID,所以我不知道它是不是有什么东西。有什么方法可以进行字符串比较吗?

编辑:我用来写入文件的代码很简单:

if(!WriteFile(hFile, sentence.c_str(), sentence.length(), &bytesWritten, NULL))
{
    //FAIL
}

文件指针需要在WriteFile()之后和ReadFile()之前重新缠绕。目前,ReadFile()没有失败,但读取零字节,因此buff保持不变。由于buff未初始化,因此它包含垃圾。要将文件指针倒带到文件的开头,请使用SetFilePointer():

#include <windows.h>
#include <iostream>
#include <string>
int main()
{
    HANDLE hFile = CreateFile ("myfile.txt",
                               GENERIC_WRITE | GENERIC_READ,
                               0,
                               NULL,
                               OPEN_EXISTING,
                               FILE_ATTRIBUTE_NORMAL,
                               NULL);
    if (hFile)
    {
        std::string sentence("a test");
        DWORD bytesWritten;
        if (WriteFile(hFile,
                      sentence.c_str(),
                      sentence.length(),
                      &bytesWritten,
                      NULL))
        {
            if (INVALID_SET_FILE_POINTER != SetFilePointer(hFile,
                                                           0,
                                                           0,
                                                           FILE_BEGIN))
            {
                char buf[128] = { 0 }; /* Initialise 'buf'. */
                DWORD bytesRead;
                /* Read one less char into 'buf' to ensure null termination. */
                if (ReadFile(hFile, buf, 127, &bytesRead, NULL))
                {
                    std::cout << "[" << buf << "]n";
                }
                else
                {
                    std::cerr << "Failed to ReadFile: " <<
                        GetLastError() << "n";
                }
            }
            else
            {
                std::cerr << "Failed to SetFilePointer: " <<
                    GetLastError() << "n";
            }
        }
        else
        {
            std::cerr << "Failed to WriteFile: " << GetLastError() << "n";
        }
        CloseHandle(hFile);
    }
    else
    {
        std::cerr << "Failed to open file: " << GetLastError() << "n";
    }
    return 0;
}

函数返回true,因此它正在从文件中读取。问题是buff充满了正义感。

CCD_ 7仅填充缓冲器直到CCD_。如果你试图使用一个字符串,那么在ReadFile返回后,你必须自己用null终止它

buff [dwBytesRead] = 0;

您不应该使用128作为nNumberOfBytesToRead,因为您在打印字符串时可能会越界(或者将buff视为以0结尾的字符串)。还要检查dwBytesRead是否真的读取了那么多字节,并按照@James McLaughlin的建议0终止字符串。