課上補做:用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);
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM