写入映射文件

Write into mapped file

本文关键字:文件 映射      更新时间:2023-10-16

我正在使用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);

我在尝试写入文件时遇到运行时错误'如何 我可以正确地做到这一点吗?

错误检查可以帮助您找出错误的确切内容以及错误发生的位置。在使用之前,请确保从最后一个函数返回的值有效。

以下是为我工作的示例。您可以尝试:

在一个进程中创建文件映射。

HANDLE hFile = CreateFileA(
"test.txt", // file name
GENERIC_READ | GENERIC_WRITE, // access type
0, // other processes can't share
NULL, // security
OPEN_EXISTING, // open only if file exists
FILE_ATTRIBUTE_NORMAL,
NULL);
if (hFile == INVALID_HANDLE_VALUE)
printf("CreateFileA error: %d n", GetLastError());

// 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
if (hMapFile == NULL)
printf("CreateFileMapping error: %d n", GetLastError());
getchar();

在另一个中打开文件映射。

HANDLE hFile = OpenFileMapping(FILE_MAP_WRITE, TRUE, L"myFile");
if (hFile == NULL)
printf("OpenFileMapping error: %d n", GetLastError());
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
if (lpMapAddress == NULL)
printf("MapViewOfFile error: %d n", GetLastError());
char newData[] = "Z";
snprintf((char*)lpMapAddress, sizeof(newData), newData);
UnmapViewOfFile(lpMapAddress);
CloseHandle(hFile);