我有一个c ++类,使用stat读取有关文件的信息。它在各自的文件上设置dir和reg true就好了,但是当我在我的ubuntu PC上的已知sym链接上测试时,lnk仍然是假的(" /vmlinuz.old")。它在这种情况下设定为真。我的代码必须在此处引用: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();
}
}
};
答案 0 :(得分:1)
如果我没有弄错,你使用stat()系统调用来检查文件是否是符号链接,使用S_IFLNK标志。以下是手册页中的引用:
stat() stats the file pointed to by path and fills in buf.
lstat() is identical to stat(), except that if path is a symbolic link,
then the link itself is stat-ed, not the file that it refers to.
尝试使用lstat()而不是stat()。 stat()跟在链接之后,并返回链接链接到的文件确实是目录或常规文件。
答案 1 :(得分:1)
stat()
返回有关符号链接指向的文件的信息...尝试lstat()