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

前端 未结 8 966
孤城傲影
孤城傲影 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

    The system() call is a strange beast. I have been bitten by a NOP system() implementation on a Mac many moons ago. It's implementation defined meaning the standard doesn't define what an implementation (platform/compiler) is supposed to do. Unfortunately, this is also about the only standard way of doing something outside the scope of your function (in your case -- changing the permissions).

    Update: A proposed hack:

    • Create a non-empty file with appropriate permissions on your system.

    • Use Boost Filesystem's copy_file to copy this file out to your desired output.

      void copy_file(const path& frompath, const path& topath): The contents and attributes of the file referred to by frompath is copied to the file referred to by topath. This routine expects a destination file to be absent; if the destination file is present, it throws an exception. This, therefore, is not equivalent to the system specified cp command in UNIX. It is also expected that the frompath variable would refer to a proper regular file. Consider this example: frompath refers to a symbolic link /tmp/file1, which in turn refers to a file /tmp/file2; topath is, say, /tmp/file3. In this situation, copy_file will fail. This is yet another difference that this API sports compared to the cp command.

    • Now, overwrite the output with actual contents.

    But, this is only a hack I thought of long after midnight. Take it with a pinch of salt and try this out :)

提交回复
热议问题