您的位置:首页 > 编程语言 > C语言/C++

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

2012-08-13 23:56 761 查看
都是默认相对路径(程序所在路径)

【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。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  mfc api c++ struct 文档 c#