Alex Rivera | Logout

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

Asked 2009-02-26T21:07:52.190
25

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 system("chmod 700 file.txt"); but I need this code to work on Windows as well. I can use some Windows api; but what is the best c++ cross platform way to do this?

Edit
Report

2 Answers

3

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 :)

answered 2009-02-26T21:23:32.980
1

I just found a couple of ways to do chmod 700 easily from the Windows command line. I'm going to post another question asking for help coming up with an equivalent win32 security descriptor structure to use (if I can't figure it out in the next few hours).

Windows 2000 & XP (messy- it always seems to prompt):

echo Y|cacls *onlyme.txt* /g %username%:F

Windows 2003+:

icacls *onlyme.txt* /inheritance:r /grant %username%:r

EDIT:

If you had the ability to use the ATL, this article covers it (I don't have Visual Studio available): http://www.codeproject.com/KB/winsdk/accessctrl2.aspx

Actually, it says the sample code includes non-ATL sample code as well- it should have something that works for you (and me!)

The important thing to remember is to get r/w/x for owner only on win32, you just have to wipe all of the security descriptors from the file and add one for yourself with full control.

answered 2009-11-25T18:22:08.077

Your Answer