【发布时间】:2018-03-23 07:10:28
【问题描述】:
当我尝试使用ReadFile() Windows API 打开“.exe”文件时,它只是返回文件的第 2 个字符,例如:MZ
这是我的代码:
#define BUFFERSIZE 5000
VOID CALLBACK FileIOCompletionRoutine(
__in DWORD dwErrorCode,
__in DWORD dwNumberOfBytesTransfered,
__in LPOVERLAPPED lpOverlapped
);
VOID CALLBACK FileIOCompletionRoutine(
__in DWORD dwErrorCode,
__in DWORD dwNumberOfBytesTransfered,
__in LPOVERLAPPED lpOverlapped)
{
_tprintf(TEXT("Error code:\t%x\n"), dwErrorCode);
_tprintf(TEXT("Number of bytes:\t%x\n"), dwNumberOfBytesTransfered);
g_BytesTransferred = dwNumberOfBytesTransfered;
}
HANDLE hFile;
DWORD dwBytesRead = 0;
char ReadBuffer[BUFFERSIZE] = { 0 };
OVERLAPPED ol = { 0 };
hFile = CreateFile(fullFilePath.c_str(), // file to open
GENERIC_READ, // open for reading
FILE_SHARE_READ, // share for reading
NULL, // default security
OPEN_EXISTING, // existing file only
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, // normal file
NULL); // no attr. template
ReadFileEx(hFile, ReadBuffer, BUFFERSIZE - 1, &ol, FileIOCompletionRoutine);
当我打印ReadBuffer 时,它只是MZ(exe 文件)。
但使用:
std::ifstream file(argv[1], std::ios::in | std::ios::binary);
它工作得很好。 如何使用 ReadFile 读取二进制文件?
【问题讨论】:
-
如何打印
ReadBuffer?作为一个以 NUL 结尾的字符串,我怀疑。当然不是。 -
@IgorTandetnik 我将
ReadBuffer的值放入字符串并使用std::cout打印字符串 -
没错。您将其打印为文本数据,但它是二进制数据。它可能在
MZ之后有一个零字节,并且打印在那里停止。 -
@IgorTandetnik 我是这么认为的,因为当我用记事本打开 EXE 文件时,它在 MZ 之后是
NULL。如何忽略NULL字符?还是删除它? -
而不是
std::string val{buffer};使用std::string val{buffer, buffer+dwBytesRead};