1 #include<stdio.h> 2 #include<stdlib.h> 3 #include<Windows.h> 4 5 char path[256] = "kaifang.txt"; 6 7 void main() 8 { 9 //路径,读写, 10 HANDLE hfile = CreateFileA(path, GENERIC_READ | GENERIC_WRITE, 0, NULL, 11 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);//打开一个文件 12 13 //如果打开失败 14 if (hfile ==INVALID_HANDLE_VALUE) 15 { 16 printf("打开文件失败"); 17 system("pause"); 18 } 19 //获取文件大小 20 printf("\n%d", GetFileSize(hfile,NULL)); 21 //创建映射 22 HANDLE hmap = CreateFileMappingA(hfile, 23 NULL, PAGE_READWRITE | SEC_COMMIT,//读写 24 0, 25 GetFileSize(hfile, NULL) + 1,//文件大小多一位 26 NULL); 27 //判断是否映射失败 28 if (hmap==NULL) 29 { 30 printf("映射失败"); 31 CloseHandle(hfile); 32 system("pause"); 33 } 34 //创建一个指针,存储映射以后的首地址 35 PVOID pvfile = MapViewOfFile(hmap, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, 0); 36 37 if (pvfile==NULL) 38 { 39 printf("指针映射失败"); 40 CloseHandle(hfile); 41 CloseHandle(hmap); 42 system("pause"); 43 44 } 45 46 puts("映射成功"); 47 char *pstart = pvfile;//首地址 48 char *pend = pstart + GetFileSize(hfile, NULL);//结束地址 49 system("pause"); 50 51 char str[100] = "test test"; 52 memcpy(pend, str, strlen(str)); 53 54 55 system("pause"); 56 UnmapViewOfFile(pvfile);//解除映射 57 CloseHandle(hmap); 58 system("pause"); 59 60 }