Skip to content

Instantly share code, notes, and snippets.

@Bak-Jin-Hyeong
Last active May 11, 2017 06:10
Show Gist options
  • Save Bak-Jin-Hyeong/bc01db49566ee5a605a1dab1583ad04d to your computer and use it in GitHub Desktop.
Save Bak-Jin-Hyeong/bc01db49566ee5a605a1dab1583ad04d to your computer and use it in GitHub Desktop.
#include <io.h>
#include <fcntl.h>
#include <Windows.h>
auto open_file_for_read_alow_delete(const wchar_t filename[]) {
struct result {
FILE* fp;
long long size;
int error;
};
auto h = ::CreateFileW(filename,
GENERIC_READ,
FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
nullptr, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, nullptr);
if (h == INVALID_HANDLE_VALUE) {
auto win32_error = ::GetLastError();
return result{ nullptr, 0, HRESULT_FROM_WIN32(win32_error) };
}
LARGE_INTEGER size = {};
if (!::GetFileSizeEx(h, &size)) {
auto win32_error = ::GetLastError();
::CloseHandle(h);
return result{ nullptr, size.QuadPart, HRESULT_FROM_WIN32(win32_error) };
}
auto fd = _open_osfhandle(
reinterpret_cast<intptr_t>(h), _O_RDONLY | _O_BINARY | _O_SEQUENTIAL);
if (fd == -1) {
const auto e = errno;
::CloseHandle(h);
return result{ nullptr, size.QuadPart, e };
}
auto fp = _fdopen(fd, "rb");
if (!fp) {
const auto e = errno;
_close(fd);
return result{ nullptr, size.QuadPart, e };
}
return result{ fp, size.QuadPart, 0 };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment