生活随笔
收集整理的這篇文章主要介紹了
遍历可执行文件所在目录下的指定类型的文件
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
示例:遍歷可執行文件目錄下指定的txt類型的文件,編譯環境vs2010,項目類型控制臺輸出程序;
代碼實現:
main.cpp
#include "stdafx.h"
#include <iostream>
#include <windows.h>
#include <io.h>
using namespace std
;
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
);char *psText
; psText
= new char[dwNum
];WideCharToMultiByte
(CP_OEMCP
,NULL,wText
,-1,psText
,dwNum
,NULL,FALSE
);szDst
= psText
;delete []psText
;
}
string
GetFilePath()
{wchar_t filePath
[100];string strFilePath
;DWORD ret
= GetModuleFileName(NULL,filePath
,100);if (ret
!= 0){Wchar_tToString(strFilePath
,filePath
); }else{strFilePath
= "文件的路徑為空!";} return strFilePath
;
}
string
GetFileDir(string strPath
)
{int nPos
= strPath
.find_last_of('\\');strPath
= strPath
.substr(0,nPos
+1);return strPath
;
}
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); _findclose(handle
);} }int _tmain(int argc
, _TCHAR
* argv
[])
{string strFilePath
= GetFilePath();string strPath
= GetFileDir(strFilePath
);DocumentTraveral(strPath
);system("pause");return 0;
}
總結:
此博文中涉及到文件夾遍歷,文件打開讀寫關閉相關的,字符串截取操作,做以記錄,方便使用。
總結
以上是生活随笔為你收集整理的遍历可执行文件所在目录下的指定类型的文件的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。