0

我尝试使用这种方法:

#include <windows.h>
#include <iostream>

int main() {
  LARGE_INTEGER size;
  HANDLE hFile = CreateFile("c:\\pagefile.sys", GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  if (hFile == INVALID_HANDLE_VALUE) return(1);
  GetFileSizeEx(hFile, &size);
  CloseHandle(hFile);
  std::cout << size.QuadPart << std::endl;
}

但正如你所见,我指向被锁定的“pagefile.sys”,程序遇到 INVALID_HANDLE_VALUE。但非系统应用程序可以看到锁定文件的大小。例如,总指挥官给了我大约 1GB,它必须从某个地方获取这个值(更不用说简单的右键单击该文件,但那是系统进程,因此文件没有被锁定)。那么,这种情况下是否有任何 winapi 调用?

我已经更新了代码以包含建议的更正,但它仍然不起作用:

#include <windows.h>
#include <iostream>

int main() {
  LARGE_INTEGER size;
  HANDLE hFile = CreateFile("c:\\pagefile.sys", 0, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  std::cout << "GetLastError: " << GetLastError() << std::endl;
  //says: 5 (0x5) ERROR_ACCESS_DENIED
  if (hFile == INVALID_HANDLE_VALUE) return(1);
  GetFileSizeEx(hFile, &size);
  CloseHandle(hFile);
  std::cout << size.QuadPart << std::endl;
}
4

2 回答 2

6

您可以从文件的目录条目中获取信息,没有机制可以锁定它。这需要 FindFirstFile/FindNextFile 来迭代目录。返回的 WIN32_FIND_DATA.nFileSizeHigh/Low 为您提供所需的信息。

The actual number you get is not reliable, it is merely a snapshot and it is likely to be stale. Especially so for the paging file, Windows can rapidly change its size. Getting a reliable size requires locking the file so nobody can change it, like you did. Which will not work for the paging file, the operating system keeps a hard lock on it so nobody can mess with the file content or read security sensitive data from the file.

于 2013-02-02T16:34:16.217 回答
0

According to MSDN, you should set the dwDesiredAccess parameter to 0 (zero) if you only want information without opening the file.

于 2013-02-02T16:35:08.057 回答