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

ε祈祈猫儿з 提交于 2020-01-15 07:27:26

问题


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?


回答1:


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.




回答2:


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.




回答3:


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

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




回答4:


  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.



来源:https://stackoverflow.com/questions/6274598/how-do-i-set-file-permissions-when-opening-a-file-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!