C语言遍历文件夹中的文件

dpstill 2014-10-19 09:44:36
请教各位大侠,

使用c语言,遍历某个文件夹中的文件,例如,我想遍历c:\doc\*.txt。遍历需要满足如下的条件:
1) 不是使用c++的方法,struct _finddata_t fileinfo; 好像是c++的方法,我不希望使用这个方法。也不希望使用dos命令。
2) c遍历的方法,在windows和linux上都能使用。或者说,在windows可以使用,稍微修改一下,到linux下也能使用。
...全文
260 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
smartjeckk 2014-10-21
  • 打赏
  • 举报
回复

int AddFileIntoStream(char *basePath,struct *st)
{
	DIR *dir;
	struct dirent *ptr;
	char base[1000];

	if ((dir=opendir(basePath)) == NULL){
		return -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*/
		{	
		   // 当前目录文件
		}
		else if(ptr->d_type == 10)	  /*link file*/
		{
	
		}

		else if(ptr->d_type == 4)	 /*dir*/
		{
			memset(base,'\0',sizeof(base));
			strcpy(base,basePath);
			strcat(base,"/");
			strcat(base,ptr->d_name);
			AddFileIntoStream(base , st);
		}
	}
	closedir(dir);
	return 1;
}
赵4老师 2014-10-20
  • 打赏
  • 举报
回复
system("dir /b /a-d c:\\*.* >d:\\allfiles.txt"); //读文件d:\\allfiles.txt的内容即C:\\下所有文件的名字 system("dir /b /a-d /s c:\\*.* >d:\\allfilesinsub.txt"); //读文件d:\\allfilesinsub.txt的内容即C:\\下所有文件的名字包含子目录 system("dir /b /ad c:\\*.* >d:\\alldirs.txt"); //读文件d:\\alldirs.txt的内容即C:\\下所有子目录的名字 请记住,能用shell命令获取文件、文件夹信息或者操作文件、文件夹最好用shell命令获取或者操作,而不要用各种API获取或者操作,因为当遇到非法文件夹名或非法文件名或非法文件长度、非法文件日期、压缩文件、链接文件、稀疏文件……等各种意料之外的情况时,API会处理的不全面或陷入死循环,而shell命令不会。
赵4老师 2014-10-20
  • 打赏
  • 举报
回复
Windows下用dir Linux下用ls
帅气小小少 2014-10-20
  • 打赏
  • 举报
回复
引用 4 楼 slx_391987 的回复:
linux下可以使用readdir函数。参考代码如下:

int travelDir(const char *pcDirName)
{
    struct dirent *pstDirent = NULL;
    DIR* pDir = NULL; 
    
    if (NULL == pcDirName)
    {
        return -1;
    }

    pDir = opendir(pcDirName);
    if (NULL == pDir)
    {
        return -1;
    }

    while (NULL != (pstDirent=readdir(pDir)))
    {
        printf("%s\n", pstDirent->d_name);
    }

    return 0;
}
忘记 closedir 了,呵呵
帅气小小少 2014-10-20
  • 打赏
  • 举报
回复
linux下可以使用readdir函数。参考代码如下:

int travelDir(const char *pcDirName)
{
    struct dirent *pstDirent = NULL;
    DIR* pDir = NULL; 
    
    if (NULL == pcDirName)
    {
        return -1;
    }

    pDir = opendir(pcDirName);
    if (NULL == pDir)
    {
        return -1;
    }

    while (NULL != (pstDirent=readdir(pDir)))
    {
        printf("%s\n", pstDirent->d_name);
    }

    return 0;
}
luotuo44 2014-10-20
  • 打赏
  • 举报
回复
C语言标准库里面没有关于文件夹的操作的函数,所以只能使用系统本身提供的操作函数。Windows和Linux提供的文件夹函数差别很大,不能稍微修改就能在Linux上使用。
brookmill 2014-10-19
  • 打赏
  • 举报
回复
1. 可以用findfirst findnext http://bbs.csdn.net/topics/10288987 2. 没有linux和windows通用的方法吧?两个不同的系统,各有其接口,应该不能通用的。如果有的话,我也很想知道。 linux里面用opendir readdir之类的

69,369

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧