C++實現從一個檔案夾中讀出所有txt檔案

來源:互聯網
上載者:User

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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.