示例:遍历可执行文件目录下指定的txt类型的文件,编译环境vs2010,项目类型控制台输出程序;
代码实现:
main.cpp
// DocumentTraveral_demo.cpp : 定义控制台应用程序的入口点。#include "stdafx.h"
#include <iostream>
#include <windows.h>
#include <io.h>
using namespace std;//wchar_t转换为string
void Wchar_tToString(std::string& szDst, wchar_t *wchar)
{wchar_t * wText = wchar;DWORD dwNum = WideCharToMultiByte(CP_OEMCP,NULL,wText,-1,NULL,0,NULL,FALSE);// WideCharToMultiByte的运用char *psText; // psText为char*的临时数组,作为赋值给std::string的中间变量psText = new char[dwNum];WideCharToMultiByte (CP_OEMCP,NULL,wText,-1,psText,dwNum,NULL,FALSE);// WideCharToMultiByte的再次运用szDst = psText;// std::string赋值delete []psText;// psText的清除
}//获取当前文件的路径
string GetFilePath()
{wchar_t filePath[100];string strFilePath;DWORD ret = GetModuleFileName(NULL,filePath,100);//GetCurrentDirectory();获取可执行文件所在绝对路径if (ret != 0)//不等于0 成功{Wchar_tToString(strFilePath,filePath); }else//返回值为0失败{strFilePath = "文件的路径为空!";} return strFilePath;
}//获取某文件所在路径中的文件夹路径,即F:\self_study\DocumentTraveral_demo\Debug\1.txt 函数返回F:\self_study\DocumentTraveral_demo\Debug\
string GetFileDir(string strPath)
{int nPos = strPath.find_last_of('\\');strPath = strPath.substr(0,nPos+1);return strPath;
}
//遍历指定文件夹strPath下指定类型*.txt的文件void DocumentTraveral(string &strPath){struct _finddata64i32_t fileInfo;char data[100];memset(data,0,100);FILE * fp;string strTemp = strPath;string str = strTemp;long handle = _findfirst(strPath.append("*.txt").c_str(),&fileInfo);if(handle != -1){do {fp = fopen(strTemp.append(fileInfo.name).c_str(),"r");if (fp != NULL){while (!feof(fp))//文件到尾为真{fgets(data,sizeof(data),fp);cout<<"文件的内容:"<<data<<endl;}fclose(fp);strTemp = str;}} while (_findnext(handle,&fileInfo) != -1); //失败-1,成功0 _findclose(handle);} }int _tmain(int argc, _TCHAR* argv[])
{string strFilePath = GetFilePath();string strPath = GetFileDir(strFilePath);DocumentTraveral(strPath);system("pause");return 0;
}
总结:
此博文中涉及到文件夹遍历,文件打开读写关闭相关的,字符串截取操作,做以记录,方便使用。