1. 程式人生 > >課上補做:用C語言程式設計實現ls命令

課上補做:用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\n", 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/\n", depth, "", entry->d_name);
            printdir(entry->d_name, depth+4);
        }
        else printf("%*s%s\n", 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);
}