linux C读目录下面 的 所有文件名字

本文介绍如何使用C语言在Linux环境下读取指定目录下的所有文件及子目录名称,包括利用dirent.h库中的结构体和函数进行操作,以及如何递归地处理子目录。

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

任务需求: 读取某个目录下的所有文件的名字,并且将读取的名字,作为参数逐个传入处理函数

需要考虑的是,不同的目录下面,文件的个数不是固定的
文件名字的长度也不是固件的
那么 怎么保存这个读取的结果,并且传给其他函数使用呢。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <unistd.h>
char img_path[500][1000];
int img_num=0;
int readFileList(char *basePath)
{
    
    DIR *dir;
    struct dirent *ptr;
    //char base[1000];

    if ((dir=opendir(basePath)) == NULL)
    {
        perror("Open dir error...");
        exit(1);
    }

    while ((ptr=readdir(dir)) != NULL)
    {
        if(strcmp(ptr->d_name,".")==0 || strcmp(ptr->d_name,"..")==0)    ///current dir OR parrent dir
            continue;
        else if(ptr->d_type == 8)    ///file
            {
	       strcpy(img_path[img_num],basePath);
               strcat(img_path[img_num++],ptr->d_name);
	    }

        else 
        {
	    continue;
        }
    }
    closedir(dir);
    return 1;
}
int main()
{
    printf("Enter Image Path: ");
    fflush(stdout);
    char basePath[100]="data/";
    input=fgets(input, 256, stdin);
    if(!input) return;
    strtok(input, "\n");
    strcat(basePath,input);
    strcat(basePath,"/");
    
    readFileList(basePath);
}


实现2
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <unistd.h>
int readFileList(char *basePath)
{
    DIR *dir;
    struct dirent *ptr;
    char base[1000];

    if ((dir=opendir(basePath)) == NULL)
    {
        perror("Open dir error...");
        exit(1);
    }

    while ((ptr=readdir(dir)) != NULL)
    {
        if(strcmp(ptr->d_name,".")==0 || strcmp(ptr->d_name,"..")==0)    ///current dir OR parrent dir
            continue;
        else if(ptr->d_type == 8)    ///file
            printf("d_name:%s/%s\n",basePath,ptr->d_name);
        else if(ptr->d_type == 10)    ///link file
            printf("d_name:%s/%s\n",basePath,ptr->d_name);
        else if(ptr->d_type == 4)    ///dir
        {
            memset(base,'\0',sizeof(base));
            strcpy(base,basePath);
            strcat(base,"/");
            strcat(base,ptr->d_name);
            readFileList(base);
        }
    }
    closedir(dir);
    return 1;
}

int main(void)
{
    DIR *dir;
    char basePath[1000];

    ///get the current absoulte path
    memset(basePath,'\0',sizeof(basePath));
    getcwd(basePath, 999);
    printf("the current dir is : %s\n",basePath);

    ///get the file list
    memset(basePath,'\0',sizeof(basePath));
    strcpy(basePath,"./XL");
    readFileList(basePath);
    return 0;
}
参考网页

https://www.cnblogs.com/fnlingnzb-learner/p/6472391.html

在Linux系统下,用C语言读取当前目录下的文件名和子目录名,将名称按照ASCII码升序排序后打印到屏幕上

目标:
利用Linux命令获取当前目录下的文件和子目录名称,然后传递给C语言程序
由C语言程序对其进行排序,然后输出

https://blog.youkuaiyun.com/weixin_42730380/article/details/81103243

  1. dirent.h
    LINUX系统下的一个头文件,在这个目录下/usr/include,为了获取某文件夹目录内容,所使用的结构体。引用头文件

    #include<dirent.h>

    struct dirent
    {
    long d_ino; /* inode number 索引节点号 /
    off_t d_off; /
    offset to this dirent 在目录文件中的偏移 /
    unsigned short d_reclen; /
    length of this d_name 文件名长 /
    unsigned char d_type; /
    the type of d_name 文件类型 /
    char d_name [NAME_MAX+1]; /
    file name (null-terminated) 文件名,最长256字符 */
    }

  2. scandir()

    #include <dirent.h>
    int scandir( const char *dir,
    struct dirent ***namelist,
    int (*filter) (const void *b),
    int ( * compare )( const struct dirent **, const struct dirent ** ) );
    int alphasort(const void **a, const void **b);
    int versionsort(const void **a, const void **b);

当函数成功执行时返回找到匹配模式文件的个数,如果失败将返回-1。

函数scandir扫描dir目录下以及dir子目录下满足filter过滤模式的文件,返回的结果是compare函数经过排序的,并保存在 namelist中。注意namelist是通过malloc动态分配内存的,所以在使用时要注意释放内存。alphasort和versionsort 是使用到的两种排序的函数。

readir()也可读取列表,但是无法实现排序

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
 
void print_dir(char *path, int depth)
{
	struct dirent **name_list;
	int n = scandir(path,&name_list,0,alphasort);
    	if(n < 0)
    	{ 
   	 	printf( "scandir return %d \n",n);
    	}
    	else
    	{
    		int index=0;
    		while(index < n)
        	{
       			printf("name: %s\n", name_list[index]->d_name);
        		free(name_list[index++]);
        	}
        	free(name_list);
   	}
}
 
 
int main(int argc, char* argv[])
{
	char *now_dir, pwd[2]=".";
	if (argc != 2)
	{
		now_dir=pwd;
	}
        
	else
	{
		now_dir=argv[1];
	}	
        
    	printf("Directory scan of %s\n",now_dir);
    	print_dir(now_dir,0);
    	printf("Finish.\n");
    	exit(0);
}
 
有空 看一下 一下 函数的 底层 实现方式

strcat

				#if 0
				memset(base, '\0', sizeof(base));
				strcpy(base, basePath);
				strcat(base, "/");
				strcat(base, ptr->d_name);
				readFileList(base);
                #endif

(稍后补充)

### Linux 中打开文件目录文件的方法 在 Linux 系统中,可以通过多种方式来打开文件目录取其中的文件内容。以下是几种常用方法及其对应的示例代码。 #### 方法一:使用 `opendir` 和 `readdir` 函数 这是 C/C++ 编程中的常见做法,用于遍历指定目录下的所有文件,并可进一步取这些文件的内容。 ```c #include <stdio.h> #include <dirent.h> int main() { DIR *dir; struct dirent *entry; dir = opendir("/home/book/Linux"); // 打开目标目录 if (dir == NULL) { perror("无法打开目录"); return 1; } while ((entry = readdir(dir)) != NULL) { // 遍历目录项 printf("%s\n", entry->d_name); // 输出文件名 } closedir(dir); return 0; } ``` 上述代码展示了如何通过调用 `opendir()` 来打开一个目录,并利用循环配合 `readdir()` 获取该目录下的每一个条目名称[^1]。 #### 方法二:使用 Shell 命令组合 如果仅需简单地列出某个目录内的文件列表,则可以直接采用 shell 的内置工具完成此任务而无需编写额外程序: ```bash ls /path/to/directory | xargs cat ``` 这里,“|”管道符连接两个命令。“ls”负责列举给定路径下的所有项目;随后“xargs cat”会依次尝试打印每个项目的具体内容到终端屏幕上[^2]。 对于更复杂的场景比如递归查找子文件夹或者过滤特定类型的文档等操作来说,还可以考虑加入更多参数选项调整行为模式: ```bash find . -type f -name "*.txt" -exec cat {} \; ``` 这条语句的意思是从当前工作区(.)出发寻找(-find),限定只找常规文件(-type f),匹配扩展名为“.txt”的东西(-name ".txt") ,最后执行(cat){}动作于找到的目标上(\;)结束每轮处理过程[^4]。 #### 方法三:Python脚本实现自动化流程 除了原生支持外,在实际开发过程中也经常借助高级语言简化逻辑表达难度的同时提高跨平台兼容能力。下面给出一段基于 Python 实现相同功能的例子: ```python import os directory_path = '/home/book/Linux' for filename in os.listdir(directory_path): # 列举目录下所有的文件/子目录名字 file_full_path = os.path.join(directory_path, filename) if os.path.isfile(file_full_path): # 如果是普通文件而非特殊节点或链接之类的结构体的话... with open(file_full_path,'r') as f:# 就按照只的方式打开它咯~ print(f.read()) # 把整个文件一次性全部加载进来再吐出去吧! ``` 以上片段实现了基本的功能框架——即定位至某具体位置之后逐一访问里面的成员对象直至耗尽为止[^3]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值