我正在使用 ReadFile 读取我使用 WriteFile 写入文件的简单字符串。
有一个简单的字符串:“测试字符串,测试windows函数”。
使用 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;
}
关于c++ - ReadFile lpBuffer 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9180535/