#include <iostream>
#include <sys/stat.h>
#include <unistd.h>
#include <pwd.h>
#include <grp.h>
#include <ctime>
#include <limits.h>
// 打印文件属性信息
void printFileProperties(const struct stat& fileStat) {
// 文件类型
std::cout << "File type: ";
if (S_ISREG(fileStat.st_mode)) std::cout << "regular file\n";
else if (S_ISDIR(fileStat.st_mode)) std::cout << "directory\n";
else if (S_ISLNK(fileStat.st_mode)) std::cout << "symbolic link\n";
else std::cout << "other\n";
// 权限
std::cout << "Permissions: "
<< ((fileStat.st_mode & S_IRUSR) ? "r" : "-")
<< ((fileStat.st_mode & S_IWUSR) ? "w" : "-")
<< ((fileStat.st_mode & S_IXUSR) ? "x" : "-")
<< ((fileStat.st_mode & S_IRGRP) ? "r" : "-")
<< ((fileStat.st_mode & S_IWGRP) ? "w" : "-")
<< ((fileStat.st_mode & S_IXGRP) ? "x" : "-")
<< ((fileStat.st_mode & S_IROTH) ? "r" : "-")
<< ((fileStat.st_mode & S_IWOTH) ? "w" : "-")
<< ((fileStat.st_mode & S_IXOTH) ? "x" : "-")
<< "\n";
// 文件大小
std::cout << "File size: " << fileStat.st_size << " bytes\n";
// 文件所有者
struct passwd *pw = getpwuid(fileStat.st_uid);
struct group *gr = getgrgid(fileStat.st_gid);
std::cout << "Owner: " << (pw ? pw->pw_name : "unknown") << "\n";
std::cout << "Group: " << (gr ? gr->gr_name : "unknown") << "\n";
// 最后访问时间
std::cout << "Last accessed: " << std::ctime(&fileStat.st_atime);
// 最后修改时间
std::cout << "Last modified: " << std::ctime(&fileStat.st_mtime);
// 最后状态改变时间
std::cout << "Last status change: " << std::ctime(&fileStat.st_ctime);
}
// 获取绝对路径
std::string getAbsolutePath(const std::string& path) {
char absPath[PATH_MAX];
if (realpath(path.c_str(), absPath) == nullptr) {
perror("realpath");
return "";
}
return std::string(absPath);
}
int main() {
const char *symlinkPath = "/home/root/link.txt";
struct stat fileStat;
// 获取符号链接的目标文件路径
std::string absoluteSymlinkPath = getAbsolutePath(symlinkPath);
if (absoluteSymlinkPath.empty()) {
std::cerr << "Error: Unable to resolve symbolic link to absolute path." << std::endl;
return 1;
}
// 获取目标文件属性
if (stat(absoluteSymlinkPath.c_str(), &fileStat) == -1) {
perror("stat");
return 1;
}
printFileProperties(fileStat);
return 0;
}
C++获取软连接文件属性
于 2024-06-18 16:40:06 首次发布