LoginSignup
0
0

Windows で opendir を使う (dirent)

Last updated at Posted at 2024-04-21

これなに

いまどき Windows (Visual Studio) で C 言語だけでファイル操作をしたい!っていう縛りプレイの人向けの記事です。

Windows で C 言語 (but not C++) を学ぼうとすると wchar_t とかいうクソ時代遅れなインターフェースと格闘するハメになって無駄に初学者が悩むので、ファイル/フォルダ操作くらい char * でやらせてくれ、という話です。

縛りプレイしたくないけど?

現代の C++17 を使ってください。Modern C++ さいこう。

#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;

int main() {
	std::string path = "/path/to/directory";
	for (const auto& entry : fs::directory_iterator(path))
		std::cout << entry.path() << std::endl;
}

(そもそも C/C++ じゃなくて C# とか Rust とかを使えという説もある)

それでも私は C がいい (本題)

https://github.com/tronkko/dirent を使ってください。
これは Linux 系で使われる opendir 系の関数 (dirent.h) を Windows 上に実装したもので、中で FindFirstFileExW とかを呼び出して wcstombs_swchar_tchar * に変えてくれてます。

インストール方法

  1. https://github.com/tronkko/dirent/blob/master/include/dirent.h をコピー

  2. 「プロジェクト」→「新しい項目の追加」image.png

  3. 「ヘッダーファイル」を選んで dirent.h として追加 image.png

  4. コピーした内容を dirent.h に貼り付け

使い方

#include "dirent.h" でインクルードできます。
注意として、#include <locale.h> して setlocale(LC_CTYPE, "jpn"); しておかないと日本語が ? に化けます。

#include <stdio.h>
#include <locale.h>
#include "dirent.h"

int main(int argc, char* argv[]) {
	setlocale(LC_CTYPE, "jpn");
	char* dirname = argc < 2 ? "." : argv[1];

	DIR* dir;
	struct dirent* ent;
	dir = opendir(dirname);
	if (dir == NULL) {
		printf("%s not found\n", dirname);
		return -1;
	}
	while ((ent = readdir(dir)) != NULL) {
		switch (ent->d_type) {
		case DT_DIR:
			printf("%s (フォルダ)\n", ent->d_name);
			break;
		case DT_REG:
			printf("%s (ファイル)\n", ent->d_name);
			break;
		}
	}
	closedir(dir);

	return 0;
}

わしゃわけのわからんライブラリは使わん!

という人は素直に windows.h から FindFirstFileExW とかを直に使ってください。

References

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0