我有一个 c++ 类,它使用 stat 读取有关文件的信息。它在各自的文件上设置 dir 和 reg 为真,但当我在我的 ubuntu PC 上的已知符号链接(“/vmlinuz.old”)上测试它时,lnk 仍然为假。在这种情况下,它将 reg 设置为 true。我的代码必须在这里引用:http://linux.die.net/man/2/stat (漫步到臀部)
class file_info
{
public:
string size;
string owner;
string group;
string path;
string acc_time;
string mod_time;
string cre_time;
bool read;
bool write;
bool exec;
bool dir;
bool lnk;
bool reg;
bool fail;
private:
struct stat f_stat;
void set_size()
{
string raw_size = to_string(f_stat.st_size);
unsigned int len = raw_size.size();
size = "";
if (len <= 3)
{
size += raw_size;
size += "Bytes";
return;
}
size += raw_size[len - 1];
size += ".";
size += raw_size[len - 2];
if ((len > 3) && (len < 6)) size += "KB";
else if ((len >= 6) && (len < 9)) size += "MB";
else if ((len >= 9) && (len < 12)) size += "GB";
else if ((len >= 12) && (len < 15)) size += "TB";
else if ((len >= 15) && (len < 18)) size += "PB";
else if ((len >= 18) && (len < 21)) size += "EB";
else size = "OL";
}
private:
void get_info()
{
switch (f_stat.st_mode & S_IFMT)
{
case S_IFDIR: dir = true; break;
case S_IFREG: reg = true; break;
case S_IFLNK: lnk = true; break;
default: fail = true; break;
}
if (!fail)
{
if (f_stat.st_mode & S_IRUSR) read = true;
if (f_stat.st_mode & S_IWUSR) write = true;
if (f_stat.st_mode & S_IXUSR) exec = true;
struct passwd *pw = getpwuid(f_stat.st_uid);
struct group *gr = getgrgid(f_stat.st_gid);
if (pw != NULL) owner = pw->pw_name;
if (gr != NULL) group = gr->gr_name;
set_size();
acc_time = ctime(&f_stat.st_atime);
mod_time = ctime(&f_stat.st_mtime);
cre_time = ctime(&f_stat.st_ctime);
acc_time.erase(acc_time.end() - 1, acc_time.end());
mod_time.erase(mod_time.end() - 1, mod_time.end());
cre_time.erase(cre_time.end() - 1, cre_time.end());
}
}
public:
file_info(string file): dir(false),
lnk(false),
reg(false),
fail(false),
read(false),
write(false),
exec(false)
{
path = file;
if (stat(file.c_str(), &f_stat))
{
fail = true;
}
else
{
get_info();
}
}
};