How to give “Everyone” write permissions via C++ M

2019-06-09 17:22发布

问题:

Im struggling with changing permissions. I need, on Windows 8, to change the permissions of a file to have group "Everyone" write permissions. How to I do that? Im trying to edit a file with C++ MFC which already exists with no "Write" (Everyone) checked, thats causing me many problems.

回答1:

Your Application need to have the rights to change the permissions for the file.

#pragma comment(lib, "Advapi32.lib") 

#include "Aclapi.h"
#include "Sddl.h"
#include <io.h>
#include <sys/stat.h>

void AllowEveryone(CString path) 
{
    PACL pDacl,pNewDACL;
    EXPLICIT_ACCESS ExplicitAccess;
    PSECURITY_DESCRIPTOR ppSecurityDescriptor;
    PSID psid;

    LPTSTR lpStr;
    CString str = path;
    lpStr = str.GetBuffer();

    GetNamedSecurityInfo(lpStr, SE_FILE_OBJECT,DACL_SECURITY_INFORMATION, NULL, NULL, &pDacl, NULL, &ppSecurityDescriptor);
    ConvertStringSidToSid("S-1-1-0", &psid);

    ExplicitAccess.grfAccessMode = SET_ACCESS;
    ExplicitAccess.grfAccessPermissions = GENERIC_ALL;
    ExplicitAccess.grfInheritance = CONTAINER_INHERIT_ACE | OBJECT_INHERIT_ACE;
    ExplicitAccess.Trustee.MultipleTrusteeOperation = NO_MULTIPLE_TRUSTEE;
    ExplicitAccess.Trustee.pMultipleTrustee = NULL;
    ExplicitAccess.Trustee.ptstrName = (LPTSTR) psid;
    ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_IS_SID;
    ExplicitAccess.Trustee.TrusteeType = TRUSTEE_IS_UNKNOWN;

    SetEntriesInAcl(1, &ExplicitAccess, pDacl, &pNewDACL);
    SetNamedSecurityInfo(lpStr,SE_FILE_OBJECT,DACL_SECURITY_INFORMATION,NULL,NULL,pNewDACL,NULL);

    LocalFree(pNewDACL);
    LocalFree(psid);

    str.ReleaseBuffer();
}