我正在使用C ++和XCode创建一个cmd行应用来保存文件权限,但是我无法识别sperm()方法,错误是
'使用未声明的标识符'sperm'
我的包含和有问题的代码在下面......
// My includes ...
#include <iostream>
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <string.h>
#include <vector>
#include <sys/stat.h>
#include <dirent.h>
#include <pwd.h>
#include <grp.h>
#include <time.h>
#include <locale.h>
#include <langinfo.h>
#include <stdint.h>
// Code fragment ...
dp = opendir ("/var/someplace");
if (dp != NULL)
{
while ((ep = readdir (dp)))
{
oFile = new FileObject;
oFile->setName( ep->d_name );
oFile->setIsDirectory( ep->d_type == isFolder );
oFiles.push_back (*oFile);
// If it's a folder then we can get it's innards
if (stat(ep->d_name, &statbuf) == -1)
continue;
cout << "%10.10s", sperm(statbuf.st_mode);
iFile++;
}
closedir (dp);
}
else
perror ("Couldn't open the directory");
答案 0 :(得分:11)
这可能会让我看起来像一个变态,但我搜索谷歌的'精子'(仅适用于.h和.cpp文件)。 坏消息是我找不到任何引用(stat function页面本身除外)。
好消息是我发现this代码片段定义了它自己的“精子”功能:
char const * sperm(__mode_t mode) {
static char local_buff[16] = {0};
int i = 0;
// user permissions
if ((mode & S_IRUSR) == S_IRUSR) local_buff[i] = 'r';
else local_buff[i] = '-';
i++;
if ((mode & S_IWUSR) == S_IWUSR) local_buff[i] = 'w';
else local_buff[i] = '-';
i++;
if ((mode & S_IXUSR) == S_IXUSR) local_buff[i] = 'x';
else local_buff[i] = '-';
i++;
// group permissions
if ((mode & S_IRGRP) == S_IRGRP) local_buff[i] = 'r';
else local_buff[i] = '-';
i++;
if ((mode & S_IWGRP) == S_IWGRP) local_buff[i] = 'w';
else local_buff[i] = '-';
i++;
if ((mode & S_IXGRP) == S_IXGRP) local_buff[i] = 'x';
else local_buff[i] = '-';
i++;
// other permissions
if ((mode & S_IROTH) == S_IROTH) local_buff[i] = 'r';
else local_buff[i] = '-';
i++;
if ((mode & S_IWOTH) == S_IWOTH) local_buff[i] = 'w';
else local_buff[i] = '-';
i++;
if ((mode & S_IXOTH) == S_IXOTH) local_buff[i] = 'x';
else local_buff[i] = '-';
return local_buff;
}
用法很简单:
#include <sys/types.h>
#include <sys/stat.h>
#include <iostream>
int main(int argc, char ** argv)
{
std::cout<<sperm(S_IRUSR | S_IXUSR | S_IWGRP | S_IROTH)<<std::endl;
std::cout<<sperm(S_IRUSR)<<std::endl;
std::cout<<sperm(S_IRUSR | S_IRGRP | S_IWOTH | S_IROTH)<<std::endl;
return 0;
}
输出ideone:
r-x-w-r--
r--------
r--r--rw-
答案 1 :(得分:4)
sperm()
是Solaris上可用的非标准系统功能。但由于它不是unix标准的一部分,因此你不会在OS X上找到它。
答案 2 :(得分:2)
假设定义了该功能(并且我不打算从工作中谷歌这个名字),你打印它的方式有问题:
cout << "%10.10s", sperm(statbuf.st_mode);
这不会打印格式化的字符串,因为C ++的iostream不像C printf
那样工作。你可以不格式化它:
cout << sperm(statbuf.st_mode);
或使用printf
:
printf("%10.10s", sperm(statbuf.st_mode));
或与iostream操纵者做一些jiggery-pokery。