1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
|
/// LINK TO EITHER 'ADVAPI32.lib' FOR CL, OR 'LIBADVAPI32.a' FOR MINGW.
#include <iostream>
#include <windows.h>
#include <Aclapi.h>
void pause()
{
std::cin.sync();
std::cin.ignore();
}
class LOCK_FILE
{
public:
LOCK_FILE(TCHAR* filename): FileName(filename)
{
PACL pNewACL = NULL;
EXPLICIT_ACCESS Access[1];
BuildExplicitAccessWithName(Access, "Users", GENERIC_ALL, GRANT_ACCESS, NO_INHERITANCE);
if(SetEntriesInAcl(1, Access, NULL, &pNewACL) != ERROR_SUCCESS)
{
throw short(1);
}
if(SetNamedSecurityInfoA(FileName, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION, NULL, NULL, pNewACL, NULL) != ERROR_SUCCESS)
{
throw short(2);
}
}
~LOCK_FILE()
{
PACL pNewACL = NULL;
EXPLICIT_ACCESS Access[1];
BuildExplicitAccessWithName(&Access[0], "Users", GENERIC_ALL, DENY_ACCESS, NO_INHERITANCE);
SetEntriesInAcl(1, Access, NULL, &pNewACL);
SetNamedSecurityInfoA(FileName, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION, NULL, NULL, pNewACL, NULL);
}
private:
TCHAR* FileName;
};
int main()
{
static TCHAR* filename = "New.txt";
HANDLE hFile = NULL;
try
{
LOCK_FILE File(filename); /// FILE IS UNLOCKED FOR THE DURATION OF ITS LIFETIME WHICH, IN THIS CASE, IS THIS TRY CATCH BLOCK
hFile = CreateFile(filename, GENERIC_ALL, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); /// OPEN THE FILE IMMEDIATLY AFTER IT IS LOCKED
if(hFile == INVALID_HANDLE_VALUE)
{
throw short(3);
}
}
catch(short& Error)
{
std::cout << "ERROR FOUND AT: " << Error << " " << GetLastError() << "\n";
}
pause();
CloseHandle(hFile);
return 0;
}
|