[英]Implementing ls -R command in linux
我想知道ls -R
如何用C语言实现。 是否使用递归算法?
这是相关的代码块
<includes...>
int f_recursive; /* ls subdirectories also */
while ((ch = getopt(argc, argv, "1ABCFLRSTWabcdfghiklmnopqrstuwx")) != -1) {
switch (ch) {
.
.
.
.
case 'R':
f_recursive = 1;
break;
之后,由于上述int标志,递归完成了目录列表。
如果不跳过这些目录, 则根据情况进行递归可能会导致堆栈溢出.
和..
不过,似乎在ls.c
中没有进行任何递归。 它使用fts_children等fts-function遍历继承体系。 您可以使用相同的内容。
仅出于完整性考虑,ls是GNU coreutils的一部分:www.gnu.org/software/coreutils/。
“ ls”(至少是我所知道的实现)使用fts_open
, fts_read
...遍历文件层次结构。 这些是“非递归”方法,可在内部维护访问目录的列表。
使用“ man fts_read”或http://linux.die.net/man/3/fts_read获得有关这些功能的更多信息。
这是C语言中的简单Linux ls -R
实现。它提供与ls
类似的彩色输出
#include <stdio.h>
#include <dirent.h>
#include <string.h>
#define GREEN "\x1b[32m"
#define BLUE "\x1b[34m"
#define WHITE "\x1b[37m"
void Usage() {
fprintf(stderr, "\nUsage: exec [OPTION]... [DIR]...\n");
fprintf(stderr, "List DIR's (directory) contents\n");
fprintf(stderr, "\nOptions\n-R\tlist subdirectories recursively\n");
return;
}
void RecDir(char *path, int flag) {
DIR *dp = opendir(path);
if(!dp) {
perror(path);
return;
}
struct dirent *ep;
char newdir[512];
printf(BLUE "\n%s :\n" WHITE, path);
while((ep = readdir(dp)))
if(strncmp(ep->d_name, ".", 1))
printf(GREEN "\t%s\n" WHITE, ep->d_name);
closedir(dp);
dp = opendir(path);
while((ep = readdir(dp))) if(strncmp(ep->d_name, ".", 1)) {
if(flag && ep->d_type == 4) {
sprintf(newdir, "%s/%s", path, ep->d_name);
RecDir(newdir, 1);
}
}
closedir(dp);
}
int main(int argc, char **argv)
{
switch(argc) {
case 2:
if(strcmp(argv[1], "-R") == 0) Usage();
else RecDir(argv[1], 0);
break;
case 3:
if(strcmp(argv[1], "-R") == 0) RecDir(argv[2], 1);
else Usage();
break;
default: Usage();
}
return 0;
}
我认为这对您有帮助。
void listDir(char *dirName)
{
DIR* dir;
struct dirent *dirEntry;
struct stat inode;
char name[1000];
dir = opendir(dirName);
if (dir == 0) {
perror ("Eroare deschidere fisier");
exit(1);
}
while ((dirEntry=readdir(dir)) != 0) {
sprintf(name,"%s/%s",dirName,dirEntry->d_name);
lstat (name, &inode);
// test the type of file
if (S_ISDIR(inode.st_mode))
printf("dir ");
else if (S_ISREG(inode.st_mode))
printf ("fis ");
else
if (S_ISLNK(inode.st_mode))
printf ("lnk ");
else;
printf(" %s\n", dirEntry->d_name);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.