用C遍历文件夹下的所有文件

本文介绍了一个用于遍历指定文件夹及其子文件夹中所有文件的小程序,提供了两种实现方式,一种是使用 C++ 标准库和 io.h,另一种是使用 Windows API 函数。这些代码可以帮助开发者快速实现文件系统的遍历功能。

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

一个遍历指定文件夹下所有文件的小程序,突然用到,整理了一下,正真使用时可基于这个程序修改以符合自己的要求。下面是代码块,请指正

#include<iostream>
#include<string>
#include<io.h>
using namespace std;
/*************************************************

Function: file_search

Description: 遍历文件夹下所有的文件,包含子文件夹下的文件

Input1: string path:遍历文件夹的绝对路径

Input2: int layer:打印时前放填补空格数

Output: void

Return: void

Others: // 其它说明

*************************************************/
void file_search(string path,int layer)
{
	//struct _finddata_t 是用来存储文件各种信息的结构体
	struct _finddata_t filefind;
	
	//当前文件夹
	string curr=path+"\\*.*";
	int done=0,i,handle;

	//文件句柄初始化,找到当前文件夹 filefind.name equ "."
	if((handle=_findfirst(curr.c_str(),&filefind))==-1)return;

	//遍历当前文件夹下所有文件
	while(!(done=_findnext(handle,&filefind)))
	{
		//不检索父文件夹?(是否正确的解释)
		if(!strcmp(filefind.name,".."))continue;
		//格式对齐用
		for(i=0;i<layer;i++) cout<<"  ";
		//递归遍历
		if ((_A_SUBDIR==filefind.attrib))
		{      
			cout<<filefind.name<<"(dir)"<<endl;
			curr=path+"\\"+filefind.name;
				file_search(curr,layer+1);
		}
		else 
		{
			//打印文件名
			cout<<filefind.name<<endl;
		}
	} 
	//关闭句柄
	_findclose(handle);      
}
int main()
{    
	string path;
	cout<<"请输入目录"<<endl;
	//输入需要遍历的路径
	cin>>path;
	file_search(path,0);
	system("PAUSE");
	return 0;
} 

下面是API版本From MSDN

#define _WIN32_WINNT 0x0501
#include <Windows.h>
#include <stdio.h>
#include <malloc.h>
#include <tchar.h> 
#include <wchar.h> 
#include <strsafe.h>

#define BUFSIZE MAX_PATH

int _tmain(int argc, TCHAR *argv[])
{
   WIN32_FIND_DATA FindFileData;
   HANDLE hFind = INVALID_HANDLE_VALUE;
   DWORD dwError;
   LPTSTR DirSpec;
   size_t length_of_arg;
   INT retval;

   DirSpec = (LPTSTR) malloc (BUFSIZE);

   if( DirSpec == NULL )
   {
      printf( "Insufficient memory available\n" );
      retval = 1;
      goto Cleanup;
   }

   
   // Check for the directory to query, specified as 
   // a command-line parameter; otherwise, print usage.
   if(argc != 2)
   {
       _tprintf(TEXT("Usage: Test <dir>\n"));
      retval = 2;
      goto Cleanup;
   }

   // Check that the input is not larger than allowed.
   StringCbLength(argv[1], BUFSIZE, &length_of_arg);

   if (length_of_arg > (BUFSIZE - 2))
   {
      _tprintf(TEXT("Input directory is too large.\n"));
      retval = 3;
      goto Cleanup;
   }

   _tprintf (TEXT("Target directory is %s.\n"), argv[1]);

   // Prepare string for use with FindFile functions.  First, 
   // copy the string to a buffer, then append '\*' to the 
   // directory name.
   StringCbCopyN (DirSpec, BUFSIZE, argv[1], length_of_arg+1);
   StringCbCatN (DirSpec, BUFSIZE, TEXT("\\*"), 2*sizeof(TCHAR));

   // Find the first file in the directory.
   hFind = FindFirstFile(DirSpec, &FindFileData);

   if (hFind == INVALID_HANDLE_VALUE) 
   {
      _tprintf (TEXT("Invalid file handle. Error is %u.\n"), 
                GetLastError());
      retval = (-1);
   } 
   else 
   {
      _tprintf (TEXT("First file name is: %s\n"), 
                FindFileData.cFileName);
   
      // List all the other files in the directory.
      while (FindNextFile(hFind, &FindFileData) != 0) 
      {
         _tprintf (TEXT("Next file name is: %s\n"), 
                   FindFileData.cFileName);
      }
    
      dwError = GetLastError();
      FindClose(hFind);
      if (dwError != ERROR_NO_MORE_FILES) 
      {
         _tprintf (TEXT("FindNextFile error. Error is %u.\n"), 
                   dwError);
      retval = (-1);
      goto Cleanup;
      }
   }
   retval  = 0;

Cleanup:
   free(DirSpec);
   return retval;

}
看来以后还是要学会使用MSDN

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值