C语言目录操作

1. 在Linux下要判断一个路径是否是目录,及遍历这个路径下的所有文件,可以使用以下方式:

    主演使用的函数是:

    int lstat(const char *, struct stat):取得一个路径的信息,可以从这个信息中得到是否及目录还是文件。其他属性参考man

    S_ISDIR():判断是否是目录,传入参数是stat.st_mode

    DIR * opendir(const char *):打开指定路径

    struct dirent readdir(DIR *):打开指定目录的子路径,可以反复调用本函数来得到制定目录的所有子路径信息。当执行到最后一个目录或者文件的时候,将返回NULL

 

    综上,遍历一个目录下的所有文件的代码如下所示:

 

#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>

int main(void)
{
	struct stat fStat;
	DIR *dir;	
	struct dirent *fileInfo = NULL;	

	if (-1 == lstat("test.txt", &fStat))
	{
		perror("");
		return -1;
	}
	
	if (S_ISDIR(fStat.st_mode))
	{
		printf("INFO: The path is a directory!\n");
	}
	else
	{
		printf("INFO: The path is a file!\n");
		return 1;
	}

	//If it is a dir, print the files' names in this directory. 
	dir = opendir("test.txt");
	if (NULL == dir)
	{
		perror("");
		return -1;
	}

	fileInfo = readdir(dir);
	while (NULL != fileInfo)
	{
		printf("INFO: File name is %s!\n", fileInfo->d_name);
		fileInfo = readdir(dir);	
	}

	return 1;
}
 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值