forked from od-contrib/commander
-
Notifications
You must be signed in to change notification settings - Fork 2
/
file_info.h
74 lines (61 loc) · 1.77 KB
/
file_info.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#ifndef _COMMANDER_FILE_INFO_
#define _COMMANDER_FILE_INFO_
#include <cerrno>
#include <cstring>
#include <string>
#include <sys/stat.h>
#include "error_dialog.h"
#include "fileutils.h"
// Basic file information: whether it's a directory, executable, a symlink, file
// size, etc.
class FileInfo
{
public:
static FileInfo Get(const std::string &path);
bool symlink() const { return symlink_; }
// Symlinks are executable if they point to a valid target,
// and the target is executable.
bool executable() const
{
if (symlink_) return have_target_st_ && (target_st_.st_mode & S_IXUSR);
return st_.st_mode & S_IXUSR;
}
// For symlinks, whether the *target* is a directory.
bool directory() const
{
if (symlink_) return have_target_st_ && S_ISDIR(target_st_.st_mode);
return S_ISDIR(st_.st_mode);
}
// For symlinks, the size is that of the target,
std::size_t size() const
{
if (symlink_) return have_target_st_ ? target_st_.st_size : 0;
return st_.st_size;
}
private:
FileInfo() = default;
bool symlink_ = false;
bool have_target_st_ = false;
struct stat st_;
struct stat target_st_;
};
inline FileInfo FileInfo::Get(const std::string &path)
{
FileInfo result;
if (::lstat(path.c_str(), &result.st_) == -1)
{
ErrorDialog("lstat failed", std::strerror(errno));
return result;
}
result.symlink_ = S_ISLNK(result.st_.st_mode);
if (result.symlink_)
{
// Follow the link
if (::stat(path.c_str(), &result.target_st_) == -1)
result.have_target_st_ = false; // Points to non-existing file
else
result.have_target_st_ = true;
}
return result;
}
#endif // _COMMANDER_FILE_INFO_