C语言实现ls -l命令的源代码如下所示:
#include <stdio.h>
#include <stdlib.h>
#include <sys types.h="">
#include <dirent.h>
#include <pwd.h>
#include <grp.h>
#include <sys stat.h="">
#include <time.h>
void display_file_info(char *filename) {
struct stat statbuf;
if (stat(filename, &statbuf) == -1) {
perror(\"stat\");
return;
}
struct passwd *pw = getpwuid(statbuf.st_uid);
struct group *gr = getgrgid(statbuf.st_gid);
char timebuf[100];
strftime(timebuf, sizeof(timebuf), \"%b %d %H:%M\", localtime(&statbuf.st_mtime));
printf(\"%c%c%c%c%c%c%c%c%c%c %ld %s %s %ld %s %s\
\",
(S_ISDIR(statbuf.st_mode)) ? 'd' : '-',(statbuf.st_mode & S_IRUSR) ? 'r' : '-',(statbuf.st_mode & S_IWUSR) ? 'w' : '-',(statbuf.st_mode & S_IXUSR) ? 'x' : '-',(statbuf.st_mode & S_IRGRP) ? 'r' : '-',(statbuf.st_mode & S_IWGRP) ? 'w' : '-',(statbuf.st_mode & S_IXGRP) ? 'x' : '-',(statbuf.st_mode & S_IROTH) ? 'r' : '-',(statbuf.st_mode & S_IWOTH) ? 'w' : '-',(statbuf.st_mode & S_IXOTH) ? 'x' : '-',
statbuf.st_nlink, pw->pw_name, gr->gr_name, statbuf.st_size, timebuf, filename);
}
int main(int argc, char *argv[]) {
DIR *dir;
struct dirent *entry;
if (argc < 2) {
dir = opendir(\".\");
} else {
dir = opendir(argv[1]);
}
if (!dir) {
perror(\"opendir\");
return 1;
}
while ((entry = readdir(dir)) != NULL) {
display_file_info(entry->d_name);
}
closedir(dir);
return 0;
}
</time.h></sys></grp.h></pwd.h></dirent.h></sys></stdlib.h></stdio.h>
暂无评论