#include <stdio.h>
#include <dirent.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
int main(int argc, char const *argv[])
{
char const*path = argv[1];
struct stat s_buf;
/*獲取文件信息,把信息放到s_buf中*/
stat(path,&s_buf);
/*判斷輸入的文件路徑是否目錄,若是目錄,則往下執行,分析目錄下的文件*/
if(S_ISDIR(s_buf.st_mode))
{
printf("[%s] it is a dir\n",path);
struct dirent *filename;
DIR *dp = opendir(path);
/*readdir()必須循環調用,要讀完整個目錄的文件,readdir纔會返回NULL
若未讀完,就讓他循環*/
while(filename = readdir(dp))
{
/*判斷一個文件是目錄還是一個普通文件*/
char file_path[200];
bzero(file_path,200);
strcat(file_path,path);
strcat(file_path,"/");
strcat(file_path,filename->d_name);
/*獲取文件信息,把信息放到s_buf中*/
stat(file_path,&s_buf);
/*判斷是否目錄*/
if(S_ISDIR(s_buf.st_mode))
{
printf("[%s] is a dir\n",file_path);
}
/*判斷是否爲普通文件*/
if(S_ISREG(s_buf.st_mode))
{
printf("[%s] is a regular file\n",file_path);
}
}
}
/*若輸入的文件路徑是普通文件,則打印並退出程序*/
else if(S_ISREG(s_buf.st_mode))
{
printf("[%s] is a regular file\n",path);
return 0;
}
return 0;
}
C語言中利用絕對路徑與相對路徑讀取文件
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.