Windows XP上的ReadFile函数失败,错误代码为2
问题描述:
我有一个项目的一部分,旨在重新读取循环中的文件的某个部分(以指针移动到文件开头的前面)。开始时,代码打开文件并正确写入“最小数据”,但进一步读取(在同一文件句柄(!)中)失败,错误代码为2('文件未找到')。Windows XP上的ReadFile函数失败,错误代码为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 */
};
代码文件。 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编译的代码谢谢您的时间和建议!
答
尝试FlushFileBuffers(手柄),以提交写入磁盘你尝试阅读
答
我已经找到了问题的根源之前 - 对ReadFile的错误代码()无法在MS VC++调试器在那里进行了测试(和什么时候)该变量实际上超出了(块)范围,因此被垃圾淹没。值2只是编译器对这种情况的偏好。
我刚刚注意到并添加了一些进一步的错误检查和代码,并发现真正的错误代码是998('无效访问内存位置'),它本身来自VirtualMemBuffer类,其中VirtualAlloc调用PAGE_READONLY标志:-(。
所以,这是我的错,对不起。
谢谢大家谁花时间试图帮助我解决这个问题。
谢谢,但在已经测试甚至更多 - 该文件最初使用FILE_FLAG_NO_BUFFERING和FILE_FLAG_WRITE_THROUGH选项标志打开,它们都使cachi毫无疑问。 – MrKoin 2011-03-29 20:42:20