Filemapping和CreateFile函数实现以下功能:从1.txt中读数据,写到新文件2.txt中
时间: 2024-03-03 18:53:30 浏览: 129
设计实现对文件 file.txt的读取,插入和增加的功能
4星 · 用户满意度95%
好的,下面是一个简单的示例代码,实现从1.txt中读取数据,写到新文件2.txt中,使用Filemapping和CreateFile函数:
```
HANDLE hFile1 = CreateFile("1.txt", GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile1 == INVALID_HANDLE_VALUE)
{
printf("Error opening file. Error code: %d\n", GetLastError());
return;
}
DWORD dwFileSize = GetFileSize(hFile1, NULL);
HANDLE hMapFile = CreateFileMapping(hFile1, NULL, PAGE_READONLY, 0, 0, NULL);
if (hMapFile == NULL)
{
printf("Error creating file mapping. Error code: %d\n", GetLastError());
CloseHandle(hFile1);
return;
}
LPVOID lpMapAddress = MapViewOfFile(hMapFile, FILE_MAP_READ, 0, 0, 0);
if (lpMapAddress == NULL)
{
printf("Error mapping view of file. Error code: %d\n", GetLastError());
CloseHandle(hMapFile);
CloseHandle(hFile1);
return;
}
HANDLE hFile2 = CreateFile("2.txt", GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile2 == INVALID_HANDLE_VALUE)
{
printf("Error creating file. Error code: %d\n", GetLastError());
UnmapViewOfFile(lpMapAddress);
CloseHandle(hMapFile);
CloseHandle(hFile1);
return;
}
DWORD dwBytesWritten;
if (!WriteFile(hFile2, lpMapAddress, dwFileSize, &dwBytesWritten, NULL))
{
printf("Error writing file. Error code: %d\n", GetLastError());
}
UnmapViewOfFile(lpMapAddress);
CloseHandle(hMapFile);
CloseHandle(hFile1);
CloseHandle(hFile2);
```
注意:此示例代码仅供参考,您需要根据自己的需求进行修改。
阅读全文