在 Windows 中更改文件所有者

标签 c windows filesystems file-management

Windows 有没有类似Linux 的API chown

最佳答案

取自此处:http://www.perlmonks.org/?node_id=70562

    // #includes omitted for the sake of sanity
    HANDLE token;
    char *filename = "somefile.txt";
    char *newuser = "someuser";
    DWORD len;
    PSECURITY_DESCRIPTOR security = NULL;
    PSID sidPtr = NULL;
    int retValue = 1;

    // Get the privileges you need
    if (OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &token)) {
        SetPrivilege(token, "SeTakeOwnershipPrivilege", 1);
        SetPrivilege(token, "SeSecurityPrivilege", 1);
        SetPrivilege(token, "SeBackupPrivilege", 1);
        SetPrivilege(token, "SeRestorePrivilege", 1);
    } else retValue = 0;

    // Create the security descriptor
    if (retValue) {
        GetFileSecurity(filename, OWNER_SECURITY_INFORMATION, security, 0, &len);
        security = (PSECURITY_DESCRIPTOR)malloc(len);
        if (!InitializeSecurityDescriptor(security, SECURITY_DESCRIPTOR_REVISION))
            retValue = 0;
    }

    // Get the sid for the username
    if (retValue) {
        char domainbuf[4096];
        DWORD sidSize = 0;
        DWORD bufSize = 4096;
        SID_NAME_USE sidUse;
        LookupAccountName(NULL, newuser, sidPtr, &sidSize, domainbuf, &bufSize, &sidUse);
        sid = (PSID)malloc(sidSize);
        if (!LookupAccountName(NULL, string, (PSID)sid, &sidSize, domainbuf, &bufSize, &sidUse))
            retValue = 0;
        }
    }

    // Set the sid to be the new owner
    if (retValue && !SetSecurityDescriptorOwner(security, sidPtr, 0))
        retValue = 0;

    // Save the security descriptor
    if (retValue)
        retValue = SetFileSecurity(filename, OWNER_SECURITY_INFORMATION, security);
    if (security) free(security);
    if (sid) free(sid);
    return retValue;

`

关于在 Windows 中更改文件所有者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2220336/

相关文章:

我可以得到一些关于我用 C 实现的 strcmp() 函数的反馈吗?

c - 在 C 函数中返回二维数组

windows - fsutil - setCaseSensitiveInfo 后不支持请求

c# - Windows Phone 上的 TAEF Datadriven c# 应用程序

c - 通过/proc/mounts 监控挂载点变化

java - Jrxml 无法通过 Jar 文件读取

c - 向前兼容接口(interface)的函数签名更改

c - C 中的 srand(time()) - 调用一次?

windows - 如何获取每个文件的创建时间并格式化

linux - 文件复制时间变化