[英]How to fix the problem with alphabetical order?
Well actually im trying to replicate ls function with -la switches and i kinda got it, but there i got a huge problem, because i learned about dirent.h recently and have no idea how to get alphabetical order by file name, also formatting is bad because i want to have it "column under column".好吧,实际上我试图用 -la 开关复制 ls 函数,我有点明白了,但是我遇到了一个大问题,因为我最近了解了 dirent.h 并且不知道如何按文件名获取字母顺序,格式也是不好,因为我想让它“列下列”。 I thought about arrays, but cant imagine how it should be done.
我想过数组,但无法想象它应该如何完成。 This is the code:
这是代码:
#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);
}
So anyone have any idea how to do this?所以有人知道如何做到这一点吗?
Implement localization via #include <locale.h>
, and adding setlocale(LC_COLLATE, "");
通过
#include <locale.h>
实现本地化,并添加setlocale(LC_COLLATE, "");
(affecting only string collation/sorting) or setlocale(LC_ALL, "");
(仅影响字符串整理/排序)或
setlocale(LC_ALL, "");
near the beginning of your main()
.在
main()
的开头附近。
Then, use glob()
( man 3 glob ) without the GLOB_NOSORT flag, or scandir()
( man 3 scandir ) with alphasort
as the comparison function, and you'll get correctly sorted file names according to your current locale.然后,使用不带 GLOB_NOSORT 标志的
glob()
( man 3 glob ) 或scandir()
( man 3 scandir ) 和alphasort
作为比较函数,您将根据当前的语言环境获得正确排序的文件名。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.