建立设置文件夹权限到userGroup

来源:互联网 发布:linux 怎么重启mysql 编辑:程序博客网 时间:2024/06/09 15:32

工程中遇到Win7下建立文件夹有小锁的问题,那个文件夹建立时没设置权限。 

在网上捡到一段代码,解决了文件夹权限设置的问题.

如果在一个文件夹下建立操作文件,文件的权限默认是跟着文件夹走的.

建立设置了文件夹权限后,在此文件夹中建立操作文件时,就不用特意设置文件的权限了。效率提高很多~

/// @file       TestConsole.cpp/// @brief      建立设置文件夹权限到userGroup#include "stdafx.h"#include <windows.h>#include <tchar.h>#include <string>#include <vector>#include <accctrl.h>#include <aclapi.h>void fnTest();namespace ns_base{    BOOL CreateFullFilePath(const WCHAR * pcPathName);    BOOL IsStringLastCharMatch(const WCHAR* pcSrc, WCHAR cCharLast);    void SetFilePermissionToEveryOne(const WCHAR * pcFileName);    BOOL SetDirPermissionToEveryOne(const WCHAR * pcDirName);}int _tmain(int argc, _TCHAR* argv[]){    fnTest();    _tprintf(L"\r\nEND, press anykey to quit\r\n");    getwchar();    return 0;}void fnTest(){    const char* pContentToFile = "stuff to file";    FILE* pFile = NULL;    ns_base::CreateFullFilePath(L"c:\\test\\temp");    pFile = fopen("c:\\test\\temp\\test.txt", "wb");    if (NULL == pFile)    {        fwrite(pContentToFile, sizeof(char), strlen(pContentToFile), pFile);        fclose(pFile);    }}namespace ns_base{    BOOL CreateFullFilePath(const WCHAR * pcPathName)    {        BOOLbRc = FALSE;          std::wstringstrDir = L"";        std::wstringstrTmp;        std::vector<std::wstring> dirs;        if (NULL == pcPathName)            goto END_CreateFullFilePath;        strDir = pcPathName;        if (!ns_base::IsStringLastCharMatch(strDir.c_str(), '\\'))        {              strDir.append(L"\\");          }        //check exist        WIN32_FIND_DATA   wfd;        BOOL rValue = FALSE;        HANDLE hFind = FindFirstFile(strDir.c_str(), &wfd);        if ((hFind != INVALID_HANDLE_VALUE) && (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))        {            FindClose(hFind);            bRc = TRUE;            goto END_CreateFullFilePath;        }        FindClose(hFind);        //do the creation        for(size_t i=0; i != strDir.length(); ++i)          {              if(strDir[i] != L'\\')              {                  strTmp += strDir[i];              }              else              {                  dirs.push_back(strTmp);                  strTmp += L'\\';              }          }          for(std::vector<std::wstring>::const_iterator iter = dirs.begin(); iter != dirs.end(); ++iter)          {              // only need the last result by CreateDirectory            bRc = ns_base::SetDirPermissionToEveryOne((*iter).c_str());        }  END_CreateFullFilePath:        return bRc;      }    BOOL IsStringLastCharMatch(const WCHAR* pcSrc, WCHAR cCharLast)    {        size_t          nLen = 0;        WCHAR           cTemp = L'\0';        std::wstring    strTemp = L"";        if (NULL == pcSrc)            return FALSE;        nLen = _tcslen(pcSrc);        if (nLen <= 0)            return FALSE;        cTemp = *(pcSrc + nLen - 1);        return (cTemp == cCharLast);    }    BOOL SetDirPermissionToEveryOne(const WCHAR * pcDirName)    {        // @ref http://stackoverflow.com/questions/690780/how-to-create-directory-with-all-rights-granted-to-everyone        if(!CreateDirectory(pcDirName,NULL))            return FALSE;        HANDLE hDir = CreateFile(pcDirName,READ_CONTROL|WRITE_DAC,0,NULL,OPEN_EXISTING,FILE_FLAG_BACKUP_SEMANTICS,NULL);        if(hDir == INVALID_HANDLE_VALUE)            return FALSE;         ACL* pOldDACL;        SECURITY_DESCRIPTOR* pSD = NULL;        GetSecurityInfo(hDir, SE_FILE_OBJECT , DACL_SECURITY_INFORMATION,NULL, NULL, &pOldDACL, NULL, (void**)&pSD);        PSID pSid = NULL;        SID_IDENTIFIER_AUTHORITY authNt = SECURITY_NT_AUTHORITY;        AllocateAndInitializeSid(&authNt,2,SECURITY_BUILTIN_DOMAIN_RID,DOMAIN_ALIAS_RID_USERS,0,0,0,0,0,0,&pSid);        EXPLICIT_ACCESS ea={0};        ea.grfAccessMode = GRANT_ACCESS;        ea.grfAccessPermissions = GENERIC_ALL;        ea.grfInheritance = CONTAINER_INHERIT_ACE|OBJECT_INHERIT_ACE;        ea.Trustee.TrusteeType = TRUSTEE_IS_GROUP;        ea.Trustee.TrusteeForm = TRUSTEE_IS_SID;        ea.Trustee.ptstrName = (LPTSTR)pSid;        ACL* pNewDACL = 0;        DWORD err = SetEntriesInAcl(1,&ea,pOldDACL,&pNewDACL);        if(pNewDACL)            SetSecurityInfo(hDir,SE_FILE_OBJECT,DACL_SECURITY_INFORMATION,NULL, NULL, pNewDACL, NULL);        FreeSid(pSid);        LocalFree(pNewDACL);        LocalFree(pSD);        LocalFree(pOldDACL);        CloseHandle(hDir);        return TRUE;    }    void SetFilePermissionToEveryOne(const WCHAR * pcFileName)    {        return; ///< 由文件夹权限决定了继承的文件权限, 这里不用设置文件权限了.        // @ref http://stackoverflow.com/questions/910528/how-to-change-the-acls-from-c        // need Accctrl.h, Aclapi.h        PSID pEveryoneSID = NULL;        PACL pACL = NULL;        EXPLICIT_ACCESS ea[1];        SID_IDENTIFIER_AUTHORITY SIDAuthWorld = SECURITY_WORLD_SID_AUTHORITY;        if(NULL == pcFileName)        {            return;        }        // Create a well-known SID for the Everyone group.        AllocateAndInitializeSid(&SIDAuthWorld, 1,            SECURITY_WORLD_RID,            0, 0, 0, 0, 0, 0, 0,            &pEveryoneSID);        // Initialize an EXPLICIT_ACCESS structure for an ACE.        // The ACE will allow Everyone read access to the key.        ZeroMemory(&ea, 1 * sizeof(EXPLICIT_ACCESS));        ea[0].grfAccessPermissions = 0xFFFFFFFF;        ea[0].grfAccessMode = GRANT_ACCESS;        ea[0].grfInheritance = NO_INHERITANCE;        ea[0].Trustee.TrusteeForm = TRUSTEE_IS_SID;        ea[0].Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP;        ea[0].Trustee.ptstrName  = (LPTSTR) pEveryoneSID;        // Create a new ACL that contains the new ACEs.        SetEntriesInAcl(1, ea, NULL, &pACL);        // Initialize a security descriptor.        PSECURITY_DESCRIPTOR pSD = (PSECURITY_DESCRIPTOR) LocalAlloc(LPTR,            SECURITY_DESCRIPTOR_MIN_LENGTH);        InitializeSecurityDescriptor(pSD, SECURITY_DESCRIPTOR_REVISION);        // Add the ACL to the security descriptor.        SetSecurityDescriptorDacl(pSD,            TRUE,     // bDaclPresent flag            pACL,            FALSE);   // not a default DACL        //Change the security attributes        SetFileSecurityW(pcFileName, DACL_SECURITY_INFORMATION, pSD);        if(pEveryoneSID)        {            FreeSid(pEveryoneSID);        }        if(pACL)        {            LocalFree(pACL);        }        if(pSD)        {            LocalFree(pSD);        }    }}



0 0