【C++】カレントディレクトリ配下のファイル一覧を抽出する
実装
sample03.cpp
//============================================================================ // Name : sample03.cpp // Author : // Version : // Copyright : Your copyright notice // Description : Hello World in C++, Ansi-style //============================================================================ #include <iostream> #include <windows.h> #include <cstring> #include <unistd.h> using namespace std; int main() { cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!! // カレントディレクトリを取得 char dir[512]; getcwd(dir, 512); cout << dir << endl; // 検索パス string str = ""; str.append(dir); str.append("/work/*.txt"); // 検索データ WIN32_FIND_DATA ffData; // 検索開始 HANDLE handle = FindFirstFile(str.c_str(), &ffData); if (handle == INVALID_HANDLE_VALUE) { cout << "取得失敗" << endl; } else { cout << "取得成功" << endl; do { // ファイル名を出力する string fileInfo = ""; SYSTEMTIME stFileTime; char strFileTime[256]; // 日付を変換 FileTimeToSystemTime(&ffData.ftLastWriteTime , &stFileTime); wsprintf(strFileTime , TEXT("%d年 %d月 %d日 %d時 %d分 %d秒") , stFileTime.wYear , stFileTime.wMonth , stFileTime.wDay , stFileTime.wHour , stFileTime.wMinute , stFileTime.wSecond); // 書式整形 fileInfo.append("file:"); fileInfo.append(ffData.cFileName); fileInfo.append(" "); fileInfo.append("最終更新日時:"); fileInfo.append(strFileTime); cout << fileInfo << endl; }while(FindNextFile(handle, &ffData));// 次のファイルを検索する // ファイルハンドルを閉じる FindClose(handle); } return 0; }
ディレクトリにサンプルファイルを準備
実行結果
!!!Hello World!!! C:\pleiades\pleiades-e4.5-cpp-jre_20160312\pleiades\workspace\sample03 取得成功 file:0001.txt 最終更新日時:2017年 8月 6日 2時 55分 42秒 file:0002.txt 最終更新日時:2017年 8月 6日 2時 55分 42秒 file:0003.txt 最終更新日時:2017年 8月 6日 2時 55分 42秒 file:0004.txt 最終更新日時:2017年 8月 6日 2時 55分 42秒 file:0005.txt 最終更新日時:2017年 8月 6日 2時 55分 42秒 file:0006.txt 最終更新日時:2017年 8月 6日 2時 55分 42秒 file:0007.txt 最終更新日時:2017年 8月 6日 2時 55分 42秒 file:0008.txt 最終更新日時:2017年 8月 6日 2時 55分 42秒 file:0009.txt 最終更新日時:2017年 8月 6日 2時 55分 42秒 file:0010.txt 最終更新日時:2017年 8月 6日 2時 55分 42秒 file:0011.txt 最終更新日時:2017年 8月 6日 2時 55分 42秒