我使用Microsoft的以下代码作为模板:
#include <windows.h>
#include <stdio.h>
#include <conio.h>
#include <tchar.h>
#define BUF_SIZE 256
TCHAR szName[]=TEXT("Global\\MyFileMappingObject");
TCHAR szMsg[]=TEXT("Message from first process.");
int _tmain()
{
HANDLE hMapFile;
LPCTSTR pBuf;
hMapFile = CreateFileMapping(
INVALID_HANDLE_VALUE, // use paging file
NULL, // default security
PAGE_READWRITE, // read/write access
0, // maximum object size (high-order DWORD)
BUF_SIZE, // maximum object size (low-order DWORD)
szName); // name of mapping object
if (hMapFile == NULL)
{
_tprintf(TEXT("Could not create file mapping object (%d).\n"),
GetLastError());
return 1;
}
pBuf = (LPTSTR) MapViewOfFile(hMapFile, // handle to map object
FILE_MAP_ALL_ACCESS, // read/write permission
0,
0,
BUF_SIZE);
if (pBuf == NULL)
{
_tprintf(TEXT("Could not map view of file (%d).\n"),
GetLastError());
CloseHandle(hMapFile);
return 1;
}
CopyMemory((PVOID)pBuf, szMsg, (_tcslen(szMsg) * sizeof(TCHAR)));
_getch();
UnmapViewOfFile(pBuf);
CloseHandle(hMapFile);
return 0;
}
它运行良好,但我想使用一个名为file.txt
的文件而不是分页文件,所以我认为这些更改应该足够了:
ficheroACompartir=CreateFile("file.txt",GENERIC_READ,0,NULL,OPEN_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
if (ficheroACompartir==INVALID_HANDLE_VALUE)
{
printf("Could not open file\n");
getchar();
}
else
{
printf("File opened correctly\n");
ReadFile(ficheroACompartir,buff,4096,&dwBytesRead,NULL);
printf("%s\n",&buff); //double check that the file is opened correctly in case I'm forgetting something, content displays fine
//CloseHandle(ficheroACompartir);
}
hMapFile = CreateFileMapping(
ficheroACompartir, // use my file
NULL, // default security
PAGE_READWRITE, // read/write access
0, // maximum object size (high-order DWORD)
BUF_SIZE, // maximum object size (low-order DWORD)
szName); // name of mapping object
但是这些更改不起作用,我得到“无法创建文件映射对象”错误。
我错过了什么?
答案 0 :(得分:2)
当您调用CreateFile
打开文本文件时,您声明只需要对它的读访问权(GENERIC_READ
),因此返回的文件句柄只具有对文件的只读访问权限。然后,当您创建映射到它的文件时,您声明您想要读/写访问权限。由于文件句柄具有只读访问权限,因此无法进行此操作,文件映射也会失败。
将CreateFile
的第二个参数改为GENERIC_READ | GENERIC_WRITE
。