VirtualBox

Ticket #21967: testkeep.cpp

File testkeep.cpp, 2.8 KB (added by ron[ny], 14 months ago)
Line 
1#include <windows.h>
2#include <stdio.h>
3#include <tchar.h>
4#include <exception>
5
6void PrintLastError(int line) {
7 DWORD errorMessageID = ::GetLastError();
8 if(errorMessageID == 0) {
9 _tprintf(_T("Operation successful.\n"));
10 return;
11 }
12
13 LPTSTR messageBuffer = nullptr;
14 size_t size = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
15 NULL, errorMessageID, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&messageBuffer, 0, NULL);
16
17 _tprintf(_T("Line: %d Error code %lu: %s\n"), line, errorMessageID, messageBuffer);
18 LocalFree(messageBuffer);
19}
20
21int main() {
22 try {
23 TCHAR tempFilePath[MAX_PATH] = _T("Z:\\test.exe.tmp");
24 wchar_t finalFilePath[MAX_PATH] = L"Z:\\test.exe";
25
26 // Create a file
27 HANDLE hFile = CreateFile(tempFilePath, GENERIC_READ | GENERIC_WRITE | DELETE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
28 if (hFile == INVALID_HANDLE_VALUE) {
29 PrintLastError(__LINE__);
30 return 1;
31 }
32
33 // Create a file mapping object
34 HANDLE hMapFile = CreateFileMapping(hFile, NULL, PAGE_READWRITE, 0, 1024, NULL);
35 if (hMapFile == NULL) {
36 PrintLastError(__LINE__);
37 CloseHandle(hFile);
38 return 1;
39 }
40
41 // Map a view of the file into the address space
42 LPVOID pMapView = MapViewOfFile(hMapFile, FILE_MAP_ALL_ACCESS, 0, 0, 1024);
43 if (pMapView == NULL) {
44 PrintLastError(__LINE__);
45 CloseHandle(hMapFile);
46 CloseHandle(hFile);
47 return 1;
48 }
49 // Close the mapping handle; the mapping is still kept open.
50 CloseHandle(hMapFile);
51
52 // Write to the memory area
53 const char data[] = "Sample Data";
54 memcpy(pMapView, data, sizeof(data));
55
56 // Unmap the file
57 UnmapViewOfFile(pMapView);
58 // FlushFileBuffers(hFile);
59
60 char buf[sizeof(FILE_RENAME_INFO) + sizeof(wchar_t)*100];
61 FILE_RENAME_INFO *rename = (FILE_RENAME_INFO*)buf;
62 rename->ReplaceIfExists = 1;
63 rename->RootDirectory = 0;
64 rename->FileNameLength = wcslen(finalFilePath) * sizeof(wchar_t);
65 memcpy(rename->FileName, finalFilePath, wcslen(finalFilePath) * sizeof(wchar_t));
66
67 // Rename with SetFileInformationByHandle(FileRenameInfo)
68 if (!SetFileInformationByHandle(hFile, FileRenameInfo, buf, sizeof(buf))) {
69 PrintLastError(__LINE__);
70 CloseHandle(hFile);
71 return 1;
72 }
73 CloseHandle(hFile);
74
75 _tprintf(_T("File operation completed successfully.") );
76 return 0;
77 }
78 catch (std::exception& e) {
79 _tprintf(_T("%s\n"), e.what() );
80 return 1;
81 }
82}

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette