-3 c++ winapi createfile visual-c++ readfile
我正在Visual C ++项目中编写一个函数,该函数以2000字节为增量通过WinAPI读取文件的内容,并将其作为std :: string返回。
当文件远大于缓冲区(例如100 KB)时,会出现问题,在有效数据中间,我在文件中的多个位置添加了垃圾。这是一个长0xcccccccc...序列,由3-4个其他字节终止,通常出现在一个单词的中间。否则,该功能不会失败,并且不会丢失任何有效数据。
我没有检查确切的位置,但似乎这发生在缓冲区大小增加(或缓冲区大小增加的乘数)上。如果我将缓冲区的大小增加到大于测试文件的大小,那么问题就消失了。是什么原因导致这种情况发生?我究竟做错了什么?
std::string read_file(std::string filename) {
HANDLE hFile = CreateFile(filename.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, NULL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
std::string errortext("Error opening " + filename + ", bad handle value: " + to_string((int)hFile));
MessageBox(hwnd, errortext.c_str(), "Error", 0);
return "";
}
char buffer[2000] = "";
std::string entire_file = "";
DWORD dwBytesRead = 0;
while (ReadFile(hFile, buffer, sizeof(buffer), &dwBytesRead, NULL))
{
if (!dwBytesRead)
break;
entire_file += buffer;
}
CloseHandle(hFile);
return entire_file;
}
Run Code Online (Sandbox Code Playgroud)
entire_file += buffer;
Run Code Online (Sandbox Code Playgroud)
假设缓冲区是一个以nul结尾的字符串,在您的情况下不是。
尝试这个
entire_file.append(buffer, dwBytesRead);
Run Code Online (Sandbox Code Playgroud)
这是一个很好的示例代码,应该已经敲响了警钟,因为您没有使用dwBytesRead变量(终止循环除外)。
| 归档时间: |
|
| 查看次数: |
81 次 |
| 最近记录: |