实际上我试图用-la开关来复制ls函数,但我确实做到了,但是我遇到了一个很大的问题,因为我最近了解了dirent.h,并且不知道如何按文件名来按字母顺序排序,也格式化不好,因为我想让它“列下的列”。我想到了数组,但无法想象应该如何做。这是代码:
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <dirent.h>
#include <unistd.h>
#include <grp.h>
#include <pwd.h>
#include <time.h>
void list_dir(char *name) {
DIR *dir;
struct dirent *dp;
struct stat statbuf;
struct group *grp;
struct passwd *pwd;
char *t;
int i;
if ((dir = opendir(name)) == NULL) {
perror("Error");
}
while ((dp = readdir(dir)) != NULL) {
if (stat(dp->d_name, &statbuf) == -1)
continue;
switch (statbuf.st_mode & S_IFMT){
case S_IFBLK: printf("b"); break;
case S_IFCHR: printf("c"); break;
case S_IFDIR: printf("d"); break;
case S_IFIFO: printf("p"); break;
case S_IFLNK: printf("l"); break;
case S_IFSOCK: printf("s"); break;
default: printf("-"); break;
}
printf( (statbuf.st_mode & S_IRUSR) ? "r" : "-");
printf( (statbuf.st_mode & S_IWUSR) ? "w" : "-");
printf( (statbuf.st_mode & S_IXUSR) ? "x" : "-");
printf( (statbuf.st_mode & S_IRGRP) ? "r" : "-");
printf( (statbuf.st_mode & S_IWGRP) ? "w" : "-");
printf( (statbuf.st_mode & S_IXGRP) ? "x" : "-");
printf( (statbuf.st_mode & S_IROTH) ? "r" : "-");
printf( (statbuf.st_mode & S_IWOTH) ? "w" : "-");
printf( (statbuf.st_mode & S_IXOTH) ? "x" : "-");
printf(" %zu",statbuf.st_nlink);
if((pwd = getpwuid(statbuf.st_uid)) != NULL)
printf(" %s", pwd->pw_name);
else
printf(" %d", statbuf.st_uid);
if((grp = getgrgid(statbuf.st_gid)) != NULL)
printf(" %s", grp->gr_name);
else
printf(" %d", statbuf.st_gid);
printf(" %zu ", statbuf.st_size);
t=ctime(&statbuf.st_mtime);
for(i=4;i<=15;i++)
printf("%c",t[i]);
printf(" %s\n", dp->d_name);
}
closedir(dir);
}
int main(int argc, char **argv) {
list_dir(".");
exit(0);
}
所以有人知道如何执行此操作吗?
答案 0 :(得分:0)
通过#include <locale.h>
进行本地化,并在setlocale(LC_COLLATE, "");
的开头附近添加setlocale(LC_ALL, "");
(仅影响字符串排序/排序)或main()
。
然后,使用不带有GLOB_NOSORT标志的glob()
(man 3 glob)或带有scandir()
作为比较函数的alphasort
(man 3 scandir),您将会根据您当前的语言环境获得正确排序的文件名。