我正在使用ReadFile读取一个简单的字符串,该字符串是我使用WriteFile写入文件的。
有一个简单的字符串:“测试字符串,测试窗口函数”。
使用WriteFile将其写入文件。
现在,我想使用ReadFile确认它已写入到文件中。我需要将我读到的内容与上面的原始字符串进行比较。从我拥有的文件中读取
DWORD dwBytesRead;
char buff[128];
if(!ReadFile(hFile, buff, 128, &dwBytesRead, NULL))
//Fail该函数返回true,因此它正在从文件中读取。这个问题就是充斥着正义的声音。我以前从来没有遇到过LPVOID,所以我不知道它是不是有什么东西。有没有办法进行这种字符串比较?
编辑:我用来写入文件的代码非常简单:
if(!WriteFile(hFile, sentence.c_str(), sentence.length(), &bytesWritten, NULL))
{
//FAIL
}发布于 2012-02-08 01:58:04
文件指针需要在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;
}发布于 2012-02-08 01:09:04
该函数返回true,因此它正在从文件中读取。这个问题就是充斥着正义的声音。
ReadFile仅填充缓冲区直到dwBytesRead的值。如果您正在尝试处理字符串,则必须在ReadFile返回后自行将其为null终止:
buff [dwBytesRead] = 0;发布于 2012-02-08 01:10:51
您不应该使用128作为nNumberOfBytesToRead,因为您可以在打印字符串时越界(或者将buff视为以0结尾的字符串)。如果它真的读取那么多字节,也要检查dwBytesRead,并按照@James McLaughlin的建议以0结束字符串。
https://stackoverflow.com/questions/9180535
复制相似问题