【发布时间】:2020-01-26 21:56:34
【问题描述】:
我正在使用 windows.h 库,我使用了 2 个进程,一个应该打开一个文件,第二个进程应该将第一个字节更改为“Z”。 尝试写入文件时出现运行时错误,我该如何正确执行?
hFile = CreateFileA(
pFileName, // file name
GENERIC_WRITE, // access type
0, // other processes can't share
NULL, // security
OPEN_EXISTING, // open only if file exists
FILE_ATTRIBUTE_NORMAL,
NULL);
// create file mapping object
HANDLE hMapFile;
hMapFile = CreateFileMapping(
hFile, // file handle
NULL, // default security
PAGE_READWRITE, // read/write access
0, // maximum object size (high-order DWORD)
0, // maximum object size (low-order DWORD)
// 0 means map the whole file
L"myFile"); // name of mapping object, in case we
// want to share it
// read the file, one page at a time
这是第二个过程:
hFile = OpenFileMapping(FILE_MAP_WRITE, TRUE, L"myFile");
LPVOID lpMapAddress = MapViewOfFile(hFile, // handle to
// mapping object
FILE_MAP_ALL_ACCESS, // read/write
NULL, // high-order 32
// bits of file
// offset
NULL, // low-order 32
// bits of file
// offset
NULL); // number of bytes
sprintf((char*)lpMapAddress, "Z");
UnmapViewOfFile(lpMapAddress);
CloseHandle(hFile);
CloseHandle(hFile);
【问题讨论】:
-
您正在以仅写入权限打开文件,但您正在尝试创建具有读写页面保护的部分(即文件映射)。这将失败并拒绝访问 (5),但您不会在任何地方检查失败。
-
另外,请确定是要使用显式链接还是使用旧版 TCHAR 系统。你调用
CreateFileA,它明确使用多字节字符串API(即ANSI),并且希望pFileName是一个字节字符串。然后你使用CreateFileMapping宏而不是显式调用CreateFileMappingW(宽字符API),并且希望你定义了UNICODE,因为你传递了一个宽字符串L"myFile。 -
毫无疑问,您为什么要使用 Windows API 来实现对 STL 似乎可行的事情?也许我错过了你真正想要完成的事情。
-
@dra:C++ 标准库中没有允许进程间通信。
-
真正对你来说最大的教训是学习错误检查。在你能做到这一点之前,你根本不知道失败的原因和原因。