[英]ReadFile function on Windows XP fails with error code 2
我有一個項目的一部分,旨在以循環方式重新讀取文件的某些部分(在指針移動到文件開頭的位置之前)。 首先,代碼將打開文件並正確地在其中寫入“最小數據”,但進一步讀取(在同一文件上的句柄(!))失敗,並顯示錯誤代碼2(“未找到文件”)。
這里與該過程相關的代碼部分:
虛擬-MEM-buffer.h:
/**
* Allocates and manages page-aligned virtual memory of the given amount
*/
class VirtualMemBuffer {
public:
explicit VirtualMemBuffer(size_t size) { /* skipped */ };
/* skipped */
protected:
void * data;
public:
const void * buff() const { return this->data; };
};
頭-file.h:
static const size_t cFileSize = 4096;
typedef std::map<std::wstring, HANDLE> handlers_conrainer_type;
typedef std::pair<std::wstring, bool> item_type;
class Config {
public:
typedef std::vector<item_type > container_type;
container_type files;
/* skipped */
};
code-file.cpp(在某些函數中):
VirtualMemBuffer buffer(cFileSize);
Config config(...);
config->files.push_back(item_type(L"C:\\lock-file.lock", true));
/* skipped */
for (Config::container_type::const_iterator it = config->files.begin();
it != config->files.end();
++it)
{
HANDLE hFile = CreateFile(
(LPCWSTR)(it->first.c_str()),
GENERIC_READ | GENERIC_WRITE,
0,
NULL,
OPEN_ALWAYS,
FILE_ATTRIBUTE_NORMAL,
NULL);
if (hFile == INVALID_HANDLE_VALUE) {
DWORD error = GetLastError();
// Could not open the file, ignore it
continue;
} else {
DWORD bytes_written = 0;
BOOL write_ok = WriteFile(
hFile,
buffer.buff(),
cFileSize,
&bytes_written,
NULL);
if (!write_ok || (bytes_written != (DWORD)(cFileSize))) {
// Could not initialize the file, skip the file
CloseHandle(hFile);
continue;
};
handlers_container.insert(
std::pair<std::wstring, HANDLE>(it->first, hFile)
);
};
};
/* skipped */
for (handlers_conrainer_type::const_iterator it = handlers_container.begin();
it != handlers_container.end();
++it)
{
DWORD bytes_read = 0;
LARGE_INTEGER li;
li.HighPart = 0;
li.LowPart = 0;
BOOL move_ok = SetFilePointerEx(it->second, li, NULL, FILE_BEGIN);
BOOL read_ok = ReadFile(
it->second,
buffer.buff(),
cFileSize,
&bytes_read,
NULL);
if (!read_ok || (bytes_read != cFileSize)) {
DWORD error = GetLastError(); // error == 2 :-(
/* skipped */
};
};
如您所見,SetFilePointerEx()和ReadFile()都在同一文件句柄上運行。 第一個(以及CreateFile(),WriteFile())從未失敗,但ReadFile()從未成功。
有沒有人觀察到這種行為或至少對此有任何線索? 有什么問題,如何解決(或避免)問題?
使用MS Visual C ++ 2008 Express Edition在Windows XP SP3上編譯的代碼
感謝您的時間和建議!
我發現了問題的根源-在MS VC ++調試器中測試了ReadFile()失敗的錯誤代碼,其中(和何時)變量實際上不在(塊)范圍內,因此充滿了垃圾。 值2只是這種情況的編譯器首選項。
我剛剛注意到了這一點,並添加了一些進一步的錯誤檢查和代碼,發現真正的錯誤代碼是998(“對存儲位置的無效訪問”),它本身來自VirtualMemBuffer類,其中通過PAGE_READONLY標志調用了VirtualAlloc() :-(。
所以,這是我的錯,對不起。
感謝所有花時間嘗試幫助我解決此問題的人。
嘗試FlushFileBuffers(handle)將寫入提交到磁盤,然后再嘗試讀取它們
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.