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

c++
328
2024/1/12 13:02:29
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在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++,你需要使用该操作系统提供的相应函数来修改文件夹的访问权限。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: c++中aes加密算法有哪些特点