前言
前段時間做項目需要讀取一個文件夾里面所有的txt文件,查詢資料后得到以下實現方法:
首先了解一下這個結構體
struct _finddata_t { unsigned attrib; time_t time_create; time_t time_access; time_t time_write; _fsize_t size; char name[260];};
其中各成員變量的含義如下:
查找文件需要用到_findfirst 和 _findnext 兩個函數,這兩個函數包含在io.h庫中
1、_findfirst函數:long _findfirst(const char *, struct _finddata_t *);
第一個參數為文件名,可以用"*.*"來查找所有文件,也可以用"*.cpp"來查找.cpp文件。第二個參數是_finddata_t結構體指針。若查找成功,返回文件句柄,若失敗,返回-1。
2、_findnext函數:int _findnext(long, struct _finddata_t *);
第一個參數為文件句柄,第二個參數同樣為_finddata_t結構體指針。若查找成功,返回0,失敗返回-1。
3、_findclose()函數:int _findclose(long);
只有一個參數,文件句柄。若關閉成功返回0,失敗返回-1。
代碼及實現
需要輸出的文件
運行結果
代碼
#include <iostream>#include <string> #include <fstream> #include <io.h>using namespace stdvoid GetLineAndPrint(string in_name){ ifstream fin(in_name); if (!fin) { cerr << "open file error" << endl; exit(-1); } string str; while (getline(fin, str)) { cout << str << endl; }}int main(){ struct _finddata_t fileinfo; string in_path; string in_name; cout << "輸入文件夾路徑:" ; cin >> in_path; string curr = in_path + "//*.txt"; long handle; if ((handle = _findfirst(curr.c_str(), &fileinfo)) == -1L) { cout << "沒有找到匹配文件!" << endl; return 0; } else { in_name = in_path + "//" + fileinfo.name; GetLineAndPrint(in_name); while (!(_findnext(handle, &fileinfo))) { in_name = in_path + "//" + fileinfo.name; GetLineAndPrint(in_name); } _findclose(handle); }}
注:代碼在vs2017中編譯通過。
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對VEVB武林網的支持。
新聞熱點
疑難解答