我正在做一个项目来创建我在当前目录中的文件的数据库。我想要的关于我的文件的详细信息之一是在 ubuntu 中使用 chmod 设置的文件权限。(请注意:我也需要组和所有者信息——比如 chown——如果你能告诉我 boost 是否也可以检索所有权信息,那就太好了。)
我正在使用 boost 文件系统库,我已经检查了很多次文档,但找不到如何获取权限。
在此页面中,它显示有enum perms
文件权限字符串未显示在我自己的 filesystem.hpp 上。(并且我已经检查过我有 1.49 版本,为了确定也是从源代码构建的)。同样在同一页面上,它显示它可以获得以下权限:
perms permissions() const noexcept;
//Returns: The value of
//permissions() specified by the postconditions of the most recent call
//to a constructor, operator=, or permissions(perms) function.
我找不到权限函数,也找不到存储权限列表的位置。
这是我到目前为止的代码(实际上来自 boost 教程,但我将其修改为递归),如果您能告诉我如何获取文件权限/所有权或建议其他库而不是 boost,我将不胜感激。
编辑:我已按照 ethan_liou 的建议添加了 s.permissions() 但输出不如预期。这是更新的代码和输出。
// filesystem tut4.cpp ---------------------------------------------------------------//
// Copyright Beman Dawes 2009
// Distributed under the Boost Software License, Version 1.0.
// See http://www.boost.org/LICENSE_1_0.txt
// Library home page: http://www.boost.org/libs/filesystem
#include <iostream>
#include <iterator>
#include <vector>
#include <algorithm>
#include <boost/filesystem.hpp>
#include <stdio.h>
using namespace std;
using namespace boost::filesystem;
int read(path p);
int main(int argc, char* argv[])
{
if (argc < 2)
{
cout << "Usage: tut4 path\n";
return 1;
}
path p (argv[1]); // p reads clearer than argv[1] in the following code
read(p);
return 0;
}
int read(path p) {
try
{
if (exists(p)) // does p actually exist?
{
if (is_symlink(p)) {
cout << p << " is a link\n";
}
else if (is_regular_file(p)) {
// is p a regular file?
file_status s = status(p);
cout << p << " size is " << file_size(p) << " perms " << "" ;
printf("%o\n",s.permissions());
}
else if (is_directory(p)) // is p a directory?
{
cout << p << " is a directory containing:\n";
typedef vector<path> vec; // store paths,
vec v; // so we can sort them later
copy(directory_iterator(p), directory_iterator(), back_inserter(v));
sort(v.begin(), v.end()); // sort, since directory iteration
// is not ordered on some file systems
for (vec::const_iterator it(v.begin()), it_end(v.end()); it != it_end; ++it)
{
//cout << " " << *it << '\n';
read(*it);
}
}
else
cout << p << " exists, but is neither a regular file nor a directory\n";
}
else
cout << p << " does not exist\n";
}
catch (const filesystem_error& ex)
{
cout << ex.what() << '\n';
}
return 0;
}
输出:
$ ./a.out ~/Desktop/test
"/home/usr/Desktop/test" is a directory containing:
"/home/usr/Desktop/test/a.out" size is 69446 perms 27746424350
"/home/usr/Desktop/test/la" is a directory containing:
"/home/usr/Desktop/test/la/Untitled Document" size is 0 perms 27746424170
"/home/usr/Desktop/test/la/lala" is a directory containing:
"/home/usr/Desktop/test/la/lala/Link to lalalala" is a link
"/home/usr/Desktop/test/la/lala/Untitled Folder" is a directory containing:
"/home/usr/Desktop/test/la/lala/lalalala" size is 0 perms 0
"/home/usr/Desktop/test/test.cpp" size is 2234 perms 0
"/home/usr/Desktop/test/test.cpp~" size is 2234 perms 0
27746424350
注意:每次执行程序时,这些数字都会发生变化。