C++實現從一個檔案夾中讀出所有txt檔案
前段時間做項目需要讀取一個檔案夾裡面所有的txt檔案,查詢資料後得到以下實現方法:
首先瞭解一下這個結構體
struct _finddata_t {
unsigned attrib;
time_t time_create;
time_t time_access;
time_t time_write;
_fsize_t size;
char name[260];
};
其中各成員變數的含義如下:
unsigned atrrib: 檔案屬性的儲存位置。它儲存一個unsigned單元,用於表示檔案的屬性。檔案屬性是用位表示的,主要有以下一些:_A_ARCH(存檔)、 _A_HIDDEN(隱藏)、_A_NORMAL(正常)、_A_RDONLY(唯讀)、_A_SUBDIR(檔案夾)、_A_SYSTEM(系統)。這些都是在中定義的宏,可以直接使用,而本身的意義其實是一個無符號整型(只不過這個整型應該是2的幾次冪,從而保證只有一位為 1,而其他位為0)。既然是位表示,那麼當一個檔案有多個屬性時,它往往是通過位或的方式,來得到幾個屬性的綜合。例如唯讀+隱藏+系統屬性,應該為:_A_HIDDEN | _A_RDONLY | _A_SYSTEM 。
time_t time_create: 檔案建立時間。
time_t time_access: 檔案最後一次被訪問的時間。
time_t time_write: 檔案最後一次被修改的時間。
_fsize_t size: 檔案的大小。
char name [_MAX_FNAME ]:檔案的檔案名稱。這裡的_MAX_FNAME是一個常量宏,它在標頭檔中被定義,表示的是檔案名稱的最大長度。
尋找檔案需要用到_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 std
void 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中編譯通過。
本文永久更新連結地址:https://www.bkjia.com/Linux/2018-03/151330.htm