Linux下C遍历单个目录

本文介绍了一个C语言程序,用于在Linux环境下遍历指定的单个目录。程序通过`opendir()`、`readdir()`等函数获取目录内容,并根据`d_type`判断是文件还是目录。当遇到不同错误情况时,程序会给出相应的错误提示。此外,还提供了一个简单的Makefile用于编译和清理项目。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一个C文件:listdir.c,一个Makefile文件.

//file: listdir.c

#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <dirent.h>
#include <errno.h>


#ifdef __cplusplus
extern "C" {
#endif

#define MAX_PATH_LEN 256

int main(void)
{

char path[MAX_PATH_LEN] = {0};

DIR *dir = NULL;

struct dirent *ptr = NULL;


printf("Please input the path:");

scanf("%s", path);


if( NULL == (dir = opendir(path)) )

{

switch(errno)

{

case EACCES:

{

printf("No premium to access %s ...\n", path);

/*Add code here*/

}

break;

case ENFILE:

{

printf("Up to the number of system can open ...\n");

/*Add code here*/

}

break;

case EMFILE:

{

printf("Up to the number of process can open ...\n");

/*Add code here*/

}

break;

case ENOTDIR:

{

printf("%s is not a real dir ...\n", path);

/*Add code here*/

}

break;

case ENOENT:

{

printf("%s not exist ...\n", path);

/*Add code here*/

}

break;

default :

{

printf("Error undefined ...");

}

break;

}

goto exit_dir;

}


while( NULL != (ptr = readdir(dir)) )

{

/*file:8, dir:4*/

switch(ptr->d_type)

{

case 8:

{

printf("File:%s\n", ptr->d_name);

}

break;

case 4:

{

printf("Dir:%s\n", ptr->d_name);

}

break;

default :

{

printf("Neither a file nor a dir ...");

}

break;

}

}

closedir(dir);

return 0;


exit_dir:

closedir(dir);

return -1;

}


#ifdef __cplusplus
};
#endif


//file: Makefile

listdir : listdir.o 

gcc -o listdir listdir.o


listdir.o : listdir.c

gcc -g -Wall -c listdir.c


clean:

rm -rf listdir.o listdir

使用方法:make后运行listdir,程序提示输入要遍历的路径,输入路径后回车就可以。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值