C++、WIN API、MFC分别遍历文件夹、获取文件名称的三种方式【耿然原创】

2 篇文章 0 订阅
1 篇文章 0 订阅

都是默认相对路径(程序所在路径)

【1】C++方式:

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


int main()
{
struct _finddata_t fileinfo;
string curr="*.*";//cuu="C://xxx//yyy";
long handle;
if((handle=_findfirst(curr.c_str(),&fileinfo))==-1L)
{
 cout<<"can not find file!"<<endl;
 return 0;
}
else
{
 cout<<fileinfo.name<<endl;
 while(!(_findnext(handle,&fileinfo)))
 {
  cout<<fileinfo.name<<endl;
 }
}
_findclose(handle);
}

【2】WIN API:

#include "Shlwapi.h"
#pragma comment(lib,"Shlwapi.lib")

CFile mFile;

CString str;
mFile.Open("fileName.txt",CFile::modeCreate|CFile::modeWrite);

WIN32_FIND_DATA FindFileData;
HANDLE hFind=::FindFirstFile("*.*",&FindFileData);//"*.*"可改为其他路径
if(INVALID_HANDLE_VALUE==hFind)
 return;
while(1)
{  

  str = FindFileData.cFileName;
  str="\r\n\r\n" + str;
  mFile.SeekToEnd();
  mFile.Write(str.GetBuffer(0),str.GetLength());
  mFile.Flush();
 if(!FindNextFile(hFind,&FindFileData)) break;
}
FindClose(hFind);
mFile.Close();

【3】MFC:(这种方式的文件名有个长度限制,好像在200-300)

#include "stdafx.h"

CFile mFile;
mFile.Open("fileName.txt",CFile::modeCreate|CFile::modeWrite);
CString str;

int ok=find.FindFile(_T("*.*"));//"*.*"可改为其他路径
ok = find.FindNextFile();
while(ok)
{
 str=find.GetFileName();
 str="\r\n\r\n" + str;
 mFile.SeekToEnd();
 mFile.Write(str.GetBuffer(0),str.GetLength());
 ok = find.FindNextFile();  
}


find.Close();
mFile.Close();

注意:

(1)"*.*"可改为其他路径或格式,比如"C://tmp//*.txt"表示C盘tmp文件夹下所有的文本文档。

(2)第二个和第三个的头文件有点混合。我是新手,把两个程序写到一个文件、一个函数去了。。。

这是我知道的“C++、WIN API、MFC分别遍历文件夹、获取文件名称的三种方式”,各位还知道其他方法吗?C语言也行。但不用C#和JAVA。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值