How to set file permissions (cross platform) in C++?

前端 未结 8 981
孤城傲影
孤城傲影 2020-11-27 05:08

I am using C++ ofstream to write out a file. I want to set the permissions to be only accessible by the user: 700. In unix; I suppose I can just issue a s

8条回答
  •  醉酒成梦
    2020-11-27 05:47

    Cross-platform example to set 0700 for a file with C++17 and its std::filesystem.

    #include 
    //#include 
    #include  // Use this for most compilers as of yet.
    
    //namespace fs = std::filesystem;
    namespace fs = std::experimental::filesystem; // Use this for most compilers as of yet.
    
    int main()
    {
        fs::path myFile = "path/to/file.ext";
        try {
            fs::permissions(myFile, fs::perms::owner_all); // Uses fs::perm_options::replace.
        }
        catch (std::exception& e) {
            // Handle exception or use another overload of fs::permissions() 
            // with std::error_code.
        }           
    }
    

    See std::filesystem::permissions, std::filesystem::perms and std::filesystem::perm_options.

提交回复
热议问题