1.代码
#include <windows.h> #include <iostream> bool IsFileInUse(const std::wstring& filePath) { HANDLE hFile = CreateFileW( filePath.c_str(), GENERIC_READ, 0, // 不允许其他进程共享 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL ); if (hFile == INVALID_HANDLE_VALUE) { DWORD dwError = GetLastError(); if (dwError == ERROR_SHARING_VIOLATION) { return true; // 文件被占用 } return false; // 文件不存在或其他错误 } CloseHandle(hFile); return false; // 文件未被占用 } int main() { std::wstring filePath = L"C:\\path\\to\\your\\file.txt"; if (IsFileInUse(filePath)) { std::wcout << L"File is in use." << std::endl; } else { std::wcout << L"File is not in use." << std::endl; } return 0; }
标签:std,文件,return,filePath,占用,C++,hFile From: https://www.cnblogs.com/judes/p/18405529