实验6 仿写Linux下的ls-l命令C++实现
时间: 2024-05-16 18:13:23 浏览: 128
linux 系统命令 ls -l命令的实现
5星 · 资源好评率100%
实现类似于Linux下的ls -l命令可以使用C++的文件操作库和标准库函数实现。具体步骤如下:
1. 包含头文件
```cpp
#include <iostream>
#include <fstream>
#include <dirent.h>
#include <sys/stat.h>
#include <pwd.h>
#include <grp.h>
#include <time.h>
```
2. 定义函数
```cpp
void listDir(const char* path);
void printStat(struct stat st);
void printFileType(mode_t mode);
void printPermissions(mode_t mode);
void printTime(time_t t);
```
3. 实现函数
```cpp
void listDir(const char* path)
{
DIR* dir = opendir(path);
if (dir == NULL)
{
std::cerr << "Failed to open directory " << path << std::endl;
return;
}
dirent* entry;
while ((entry = readdir(dir)) != NULL)
{
std::string filename(entry->d_name);
if (filename == "." || filename == "..")
{
continue;
}
std::string filepath(path);
filepath += "/";
filepath += filename;
struct stat st;
if (stat(filepath.c_str(), &st) != 0)
{
std::cerr << "Failed to get file stat: " << filepath << std::endl;
continue;
}
printStat(st);
std::cout << " " << filename << std::endl;
}
closedir(dir);
}
void printStat(struct stat st)
{
printFileType(st.st_mode);
printPermissions(st.st_mode);
std::cout << " " << st.st_nlink << " ";
struct passwd* pw = getpwuid(st.st_uid);
if (pw == NULL)
{
std::cerr << "Failed to get user name" << std::endl;
return;
}
std::cout << pw->pw_name << " ";
struct group* gr = getgrgid(st.st_gid);
if (gr == NULL)
{
std::cerr << "Failed to get group name" << std::endl;
return;
}
std::cout << gr->gr_name << " ";
std::cout << st.st_size << " ";
printTime(st.st_mtime);
}
void printFileType(mode_t mode)
{
if (S_ISREG(mode))
{
std::cout << "-";
}
else if (S_ISDIR(mode))
{
std::cout << "d";
}
else if (S_ISCHR(mode))
{
std::cout << "c";
}
else if (S_ISBLK(mode))
{
std::cout << "b";
}
else if (S_ISFIFO(mode))
{
std::cout << "p";
}
else if (S_ISLNK(mode))
{
std::cout << "l";
}
else if (S_ISSOCK(mode))
{
std::cout << "s";
}
}
void printPermissions(mode_t mode)
{
std::cout << ((mode & S_IRUSR) ? "r" : "-");
std::cout << ((mode & S_IWUSR) ? "w" : "-");
std::cout << ((mode & S_IXUSR) ? "x" : "-");
std::cout << ((mode & S_IRGRP) ? "r" : "-");
std::cout << ((mode & S_IWGRP) ? "w" : "-");
std::cout << ((mode & S_IXGRP) ? "x" : "-");
std::cout << ((mode & S_IROTH) ? "r" : "-");
std::cout << ((mode & S_IWOTH) ? "w" : "-");
std::cout << ((mode & S_IXOTH) ? "x" : "-");
}
void printTime(time_t t)
{
struct tm* tm = localtime(&t);
char str[100];
strftime(str, sizeof(str), "%Y-%m-%d %H:%M:%S", tm);
std::cout << str;
}
```
4. 测试
```cpp
int main()
{
listDir(".");
return 0;
}
```
这样就可以实现类似于Linux下的ls -l命令。
阅读全文