1. 程式人生 > >簡單實現列印輸出某目錄的所有檔案

簡單實現列印輸出某目錄的所有檔案

一、 事先準備 

圖1 新建目錄檔案
圖2 在目錄檔案放3個普通檔案,3個目錄檔案

二、 程式碼實現 

#include<dirent.h>  //opendir() readdir()
#include<assert.h>  //assert()
#include<stdio.h>   //printf()
#include<sys/stat.h>	//stat()

void printfilename(mode_t mode, char *name)
{
    if(S_ISDIR(mode))	//目錄檔案 藍
	printf("\033[1;34m%s\033[0m ", name);
    else if(S_ISREG(mode))  //普通檔案
    {
	if(mode & S_IXUSR || mode & S_IXGRP || mode & S_IXOTH)//可執行 綠
	    printf("\033[1;32m%s\033[0m ", name);
	else	//不可執行
	    printf("%s ", name);
    }
}

int main()
{
    DIR *dp = opendir("mydir");	//相對路徑
    assert(NULL != dp);

    struct dirent *drt = NULL;	//指向目錄項
    
    while(NULL != (drt=readdir(dp)))	//遍歷讀取目錄的內容
    {
	struct stat st;	//將目錄項對應的內容寫入stat結構中
	stat(drt->d_name, &st);	//相對路徑
	printfilename(st.st_mode, drt->d_name);
	fflush(stdout);
    }
    printf("\n");
    return 0;
}