课上补做:用C语言编程实现ls命令

课上补做:用C语言编程实现ls命令

一、有关ls

  • ls :用来打印当前目录或者制定目录的清单,显示出文件的一些信息等。
  • ls -l :列出长数据串,包括文件的属性和权限等数据
  • ls -R:连同子目录一同显示出来,也就所说该目录下所有文件都会显示出来
  • ls -a :可以将目录下的全部文件(包括隐藏文件)显示出来
  • ls -r:将排序结果反向输出

二、参考伪代码实现ls的功能,提交代码的编译,运行结果截图。

打开目录文件
针对目录文件
   读取目录条目
   显示文件名
关闭文件目录文件
#include <unistd.h>
#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
#include <stdlib.h>

void printdir(char *dir, int depth)
{
    DIR *dp;
    struct dirent *entry;
    struct stat statbuf;

    if((dp = opendir(dir)) == NULL)
    {
        fprintf(stderr, "cannot open directory: %s
", dir);
        return;
    }
    chdir(dir);
    while((entry = readdir(dp)) != NULL)
    {
        lstat(entry->d_name, &statbuf);
        if(S_ISDIR(statbuf.st_mode))
        {
            if(strcmp(".", entry->d_name) == 0 ||
                strcmp("..", entry->d_name) == 0)
                continue;
            printf("%*s%s/
", depth, "", entry->d_name);
            printdir(entry->d_name, depth+4);
        }
        else printf("%*s%s
", depth, "", entry->d_name);
    }
    chdir("..");
    closedir(dp);
}

int main(int argc, char* argv[])
{
    char *topdir = ".";
    if (argc >= 2)
        topdir = argv[1];
    printdir(topdir, 0);
    exit(0);
}

原文地址:https://www.cnblogs.com/cxgg/p/9942462.html