温馨提示×

c++怎么修改文件夹的用户访问权限

c++
小亿
105
2023-12-13 13:02:29
栏目: 编程语言

在C++中,可以使用操作系统提供的系统调用函数来修改文件夹的用户访问权限。以下是一个使用C++和Windows操作系统的示例代码:

#include <iostream>
#include <Windows.h>

int main() {
    LPCWSTR folderPath = L"C:\\Path\\to\\Folder";

    // 获取文件夹的当前访问权限
    DWORD currentAttributes = GetFileAttributesW(folderPath);

    // 如果获取失败,输出错误消息并退出
    if (currentAttributes == INVALID_FILE_ATTRIBUTES) {
        std::cout << "Failed to get folder attributes. Error code: " << GetLastError() << std::endl;
        return 1;
    }

    // 修改访问权限为只读
    DWORD newAttributes = currentAttributes | FILE_ATTRIBUTE_READONLY;
    BOOL success = SetFileAttributesW(folderPath, newAttributes);

    // 如果修改失败,输出错误消息并退出
    if (!success) {
        std::cout << "Failed to set folder attributes. Error code: " << GetLastError() << std::endl;
        return 1;
    }

    std::cout << "Folder attributes successfully changed." << std::endl;

    return 0;
}

请注意,上述代码仅适用于Windows操作系统。如果你在其他操作系统上使用C++,你需要使用该操作系统提供的相应函数来修改文件夹的访问权限。

0