为什么 mkdir() 后跟 ofstream::operator<< 会因权限被拒绝而失败?

Why does mkdir() followed by ofstream::operator<< fail with permission denied?

以下本应是简单的程序因 errno 13: Permission denied 而失败。关于 file/directory 权限,我没有看到或不理解;谁能帮忙找出问题所在?

前言

>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

错误告诉我一些事情 回复:file/directory 权限错误,但我看不到什么。从 ls 输出来看,在我看来所有文件都归我所有,所以我不清楚为什么会出现权限被拒绝错误。请指教这里有什么问题。

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

如果你只读不执行,你可以枚举一个目录的元素,但是你不能访问它们。写而不执行对目录没有意义。