开发者

How do I set file permissions when opening a file in C++?

开发者 https://www.devze.com 2023-03-10 23:36 出处:网络
In C++, I want to open a file and set its permission, but I failed. Below is my program: string filename=开发者_运维百科\"test.cnf\";

In C++, I want to open a file and set its permission, but I failed. Below is my program:

string filename=开发者_运维百科"test.cnf";
ofstream ofile;
ofile.open(filename.c_str(),O_RDONLY);
ofile.close()

But I get the following error:

error: invalid conversion from 'int' to 'std::_Ios_Openmode'

error:   initializing argument 2 of 'void std::basic_ofstream<_CharT, _Traits>::open(const char*, std::_Ios_Openmode) [with _CharT = char, _Traits = std::char_traits<char>]'

How to set the permission of the file to such as 644, 700?


The option you seem to want to specify (O_RDONLY) isn't a "permission", it's an access mode. These are set implicitly according to the combinations of std::ios_base::in and std::ios_base::out: in alone results in O_RDONLY, out alone in O_WRONLY and in | out in O_RDWR.

For the permissions on a created file, the answer is, rather annoyingly, thet you can't specify them. std::filebuf::open() (which is what std::ifstream and std::ofstream ultimately call) has no options or provisions for passing in any indication of permissions to be used if it must create the file.
The only way to do this is by using your system level functions (open under Linux, CreateFile under Windows—despite the names, open may create a file, and CreateFile will open an existing file, without creating anything). Using system level open/CreateFile, however, means using system level read/ReadFile and write/WriteFile.


There is not O_RDONLY mode for fstream. You should use one of:

  1. ios::app
  2. ios::binary
  3. ios::ate
  4. ios::in
  5. ios::out
  6. ios::trunc

Or their combinations (say ios::app | ios::binary). For your case you should use ios::in (maybe with ios::binary). Look at this for more details.


If you are on unix systems, what you need is the "setmode" or "getmode" function.

From your shell command-line, type "man setmode"


  1. The second argument of fstream::open is a combination of flags chosen in ios::app, ios::binary, ios::ate, ios::in, ios::out, ios::trunc.

  2. There is no standard C++ interface to set the access right. The implementations I know are using 0666 which is then masked by the value set by umask(2). This is also the usual behavior of unix applications (the umask is inherited from the parent and shells have a builtin umask command). My recommandation is that you do nothing and rely on the umask set by the user. If that is not applicable, temporarily change the umask in your app.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号