m_shige1979のときどきITブログ

プログラムの勉強をしながら学習したことや経験したことをぼそぼそと書いていきます

Github(変なおっさんの顔でるので気をつけてね)

https://github.com/mshige1979

【C++】カレントディレクトリ配下のファイル一覧を抽出する

今回はC言語の勉強

いろんなところでお世話になるファイル検索
指定ディレクトリ配下の一覧を抽出することを行います。

やること

単純に指定ディレクトリ配下のディレクトリより「.txt」のファイルを検索してコンソールへ出力します。

実装

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;
}
ディレクトリにサンプルファイルを準備

f:id:m_shige1979:20170806123106j:plain

実行結果
!!!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秒

所感

toString()ない(´・ω・`)
Javaってとりあえず面倒な場合はtoString()で文字列にすればよくね?みたいな感じがあったけど
C言語ってJava以上に型に厳密な感じだな〜
もう少し楽してコード書きたいような気がしてきた〜