4.设计一个程序,要求根据输入的文件或目录(若缺省则为当前目录),实现命令“ls -l”的功能,不使用system函数。
时间: 2024-02-15 09:05:55 浏览: 29
可以使用C++的文件操作库来实现类似于“ls -l”的功能。以下是一个示例代码:
```c++
#include <iostream>
#include <fstream>
#include <dirent.h>
#include <sys/stat.h>
#include <pwd.h>
#include <grp.h>
#include <ctime>
#include <iomanip>
void ls_l(const char* path = ".") {
DIR* dir = opendir(path);
if (dir == NULL) {
std::cerr << "Failed to open directory: " << path << std::endl;
return;
}
struct dirent* entry;
while ((entry = readdir(dir)) != NULL) {
std::string name = entry->d_name;
// Skip "." and ".." directory entries
if (name == "." || name == "..") {
continue;
}
// Get file information
struct stat st;
std::string full_path = std::string(path) + "/" + name;
if (stat(full_path.c_str(), &st) != 0) {
std::cerr << "Failed to get file information: " << full_path << std::endl;
continue;
}
// Print file information
std::cout << ((S_ISDIR(st.st_mode)) ? "d" : "-") // File type
<< ((st.st_mode & S_IRUSR) ? "r" : "-") // Owner read permission
<< ((st.st_mode & S_IWUSR) ? "w" : "-") // Owner write permission
<< ((st.st_mode & S_IXUSR) ? "x" : "-") // Owner execute permission
<< ((st.st_mode & S_IRGRP) ? "r" : "-") // Group read permission
<< ((st.st_mode & S_IWGRP) ? "w" : "-") // Group write permission
<< ((st.st_mode & S_IXGRP) ? "x" : "-") // Group execute permission
<< ((st.st_mode & S_IROTH) ? "r" : "-") // Other read permission
<< ((st.st_mode & S_IWOTH) ? "w" : "-") // Other write permission
<< ((st.st_mode & S_IXOTH) ? "x" : "-") // Other execute permission
<< std::setw(2) << st.st_nlink << " "; // Number of hard links
struct passwd* pw = getpwuid(st.st_uid);
if (pw != NULL) {
std::cout << std::setw(8) << pw->pw_name << " "; // Owner name
} else {
std::cout << std::setw(8) << st.st_uid << " "; // Owner UID
}
struct group* gr = getgrgid(st.st_gid);
if (gr != NULL) {
std::cout << std::setw(8) << gr->gr_name << " "; // Group name
} else {
std::cout << std::setw(8) << st.st_gid << " "; // Group GID
}
std::cout << std::setw(10) << st.st_size << " "; // File size
char time_buf[80];
strftime(time_buf, sizeof(time_buf), "%Y-%m-%d %H:%M:%S", localtime(&st.st_mtime));
std::cout << time_buf << " "; // Last modification time
std::cout << name << std::endl; // File name
}
closedir(dir);
}
int main(int argc, char* argv[]) {
if (argc == 1) {
ls_l(".");
} else {
for (int i = 1; i < argc; i++) {
ls_l(argv[i]);
}
}
return 0;
}
```
该程序使用`opendir`和`readdir`函数来遍历目录中的文件和子目录,并使用`stat`函数获取文件信息。然后,程序使用一些C++的IO操作和格式化输出来显示文件信息,类似于“ls -l”的格式。