code / design / music and more

How to read file while it’s in use?

Let’s say you have to use a file which another process locked. You’ll get an error trying to open it. Of course there’s a workaround.
Just duplicate the handle for the current process:

// NOTE:
//
// PID is the process's ID who opened the file (ex. firefox -> 1234)
// hFile is the original file's handle (you can get it using NtQuerySystemInformation)
HANDLE hFileNew;
HANDLE hSourceProcess = OpenProcess(PROCESS_ALL_ACCESS, 0, PID);
DuplicateHandle(hSourceProcess, hFile, GetCurrentProcess(), &hFileNew, DUPLICATE_SAME_ACCESS, TRUE, DUPLICATE_SAME_ACCESS);
// Now you have a new file handle in hFileNew, which you can use with ReadFile or similar
//
// ANOTHER NOTE:
//
// hFileNew's file pointer will have the last position from PID.
// If you change it, it will change for PID too (which can cause a crash or messed up stuff).
// But if you do it fast or pause the process, everything should be fine.