【问题标题】:Why does mkdir() followed by ofstream::operator<< fail with permission denied?为什么 mkdir() 后跟 ofstream::operator<< 因权限被拒绝而失败?
【发布时间】:2018-05-02 23:49:20
【问题描述】:

以下本应简单的程序因errno 13: Permission denied 而失败。我没有看到或理解一些关于文件/目录权限的内容;任何人都可以帮助确定问题吗?

前言

>whoami
usera
>cd ~
>mkdir abc
>ls -ld abc
drwxrwxr-x 2 usera usera 4096 May  2 16:36 abc
>cd abc

代码(在当前,即“abc”目录中)

//main.cpp
#include <iostream>
#include <string>
#include <fstream>
#include <cerrno>
#include <cstdio>
#include <cstring>
#include <sys/stat.h>
#include <sys/types.h>

int main( int argc, char* argv[] )
{
  const std::string path = "./foo/";
  int result = 0;
  errno = 0;

  result = mkdir( path.c_str(), 0666 );
  std::cout << result << ": " << errno << ": " << strerror( errno ) << std::endl;
  std::string tmp = path + "fooFile";
  std::ofstream ofs( tmp.c_str(), std::ofstream::out );
  ofs << "hello, world!";
  std::cout << std::boolalpha << ofs.good() << std::endl;
  ofs.close();
  std::cout << result << ": " << errno << ": " << strerror( errno ) << std::endl;
  return 0;
}

执行

>ls -l
total 4
-rw-rw-r-- 1 usera usera 585 May  2 16:39 main.cpp

>g++ --version
g++ (GCC) 4.8.3 20140911 (Red Hat 4.8.3-7)
Copyright (C) 2013 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

>g++ -g main.cpp && ./a.out
0: 0: Success
false
0: 13: Permission denied
>
>ls -l
total 52
-rwxrwxr-x 1 usera usera 41844 May  2 16:44 a.out
drw-rw-r-- 2 usera usera  4096 May  2 16:44 foo
-rw-rw-r-- 1 usera usera   585 May  2 16:39 main.cpp

错误告诉我某事 RE:文件/目录权限错误,但我看不到什么。从ls 输出来看,在我看来所有文件都归我所有,所以我不清楚为什么会出现权限被拒绝错误。请赐教这里出了什么问题。

【问题讨论】:

  • 你能在mkdir查看回报吗?如果成功,它应该是 0(如果没有,你应该在尝试打开文件之前使用strerror)。
  • @scohe001 - 根据您的建议更新代码:mkdir() 显示成功。
  • 您需要以“超级用户”权限运行程序。
  • @raindrop7 “权限被拒绝”并不总是意味着您缺少sudo
  • mkdir() 没有失败了。

标签: c++ linux mkdir ofstream


【解决方案1】:

您need execution permissions 访问目录的内容。将您的权限参数更改为 0755 之类的内容。

如果你已经阅读而不执行,你可以枚举一个目录的元素,但你不能访问它们。不执行写入对目录毫无意义。

【讨论】:

    猜你喜欢
    • 2014-05-05
    • 1970-01-01
    • 2015-01-18
    • 2018-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-24
    相关资源
    最近更新 更多