CまたはC ++を使用してディレクトリ内のファイルのリストを取得するにはどうすればよいですか?
質問
CまたはC ++コード内からディレクトリ内のファイルのリストを確認するにはどうすればよいですか
ls
コマンドの実行およびプログラム内からの結果の解析は許可されていません。
解決
ブーストを使用しない小規模で単純なタスクでは、 dirent.h を使用します。これはWindowsでも使用できます:
DIR *dir;
struct dirent *ent;
if ((dir = opendir ("c:\\src\\")) != NULL) {
/* print all the files and directories within directory */
while ((ent = readdir (dir)) != NULL) {
printf ("%s\n", ent->d_name);
}
closedir (dir);
} else {
/* could not open directory */
perror ("");
return EXIT_FAILURE;
}
これは小さなヘッダーファイルであり、boostなどの大きなテンプレートベースのアプローチを使用せずに、必要な単純なもののほとんどを実行します(違反はありません、boostが好きです!)。
Windows互換性レイヤーの作成者はToni Ronkkoです。 Unixでは、これは標準ヘッダーです。
2017年の更新:
C ++ 17には、ファイルシステムのファイルを一覧表示する公式の方法があります:std::filesystem
。このソースコードには、以下の Shreevardhan から優れた回答があります。
#include <string>
#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 ++ 17に std::filesystem::directory_iterator
が追加されました。として使用
#include <string>
#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;
}
また、 std::filesystem::recursive_directory_iterator
もサブディレクトリを繰り返すことができます。
残念ながら、C ++標準では、この方法でファイルやフォルダを操作する標準的な方法が定義されていません。
クロスプラットフォームの方法がないため、最良のクロスプラットフォームの方法は、ブーストファイルシステムモジュール。
クロスプラットフォームブースト方式:
次の関数は、ディレクトリパスとファイル名を指定すると、ディレクトリとそのサブディレクトリでファイル名を再帰的に検索し、boolを返します。成功した場合は、見つかったファイルへのパスを返します。
bool find_file(const path & dir_path, // in this directory, const std::string & file_name, // search for this name, path & path_found) // placing path here if found { if (!exists(dir_path)) return false; directory_iterator end_itr; // default construction yields past-the-end for (directory_iterator itr(dir_path); itr != end_itr; ++itr) { if (is_directory(itr->status())) { if (find_file(itr->path(), file_name, path_found)) return true; } else if (itr->leaf() == file_name) // see below { path_found = itr->path(); return true; } } return false; }
上記のブーストページのソース。
Unix / Linuxベースのシステムの場合:
opendir / readdir / closedir 。
エントリ `` name ''をディレクトリで検索するサンプルコードは次のとおりです:
len = strlen(name); dirp = opendir("."); while ((dp = readdir(dirp)) != NULL) if (dp->d_namlen == len && !strcmp(dp->d_name, name)) { (void)closedir(dirp); return FOUND; } (void)closedir(dirp); return NOT_FOUND;
上記のマニュアルページのソースコード。
Windowsベースのシステムの場合:
Win32 API FindFirstFile / FindNextFile / FindClose 関数。
次のC ++の例は、FindFirstFileの最小限の使用方法を示しています。
#include <windows.h> #include <tchar.h> #include <stdio.h> void _tmain(int argc, TCHAR *argv[]) { WIN32_FIND_DATA FindFileData; HANDLE hFind; if( argc != 2 ) { _tprintf(TEXT("Usage: %s [target_file]\n"), argv[0]); return; } _tprintf (TEXT("Target file is %s\n"), argv[1]); hFind = FindFirstFile(argv[1], &FindFileData); if (hFind == INVALID_HANDLE_VALUE) { printf ("FindFirstFile failed (%d)\n", GetLastError()); return; } else { _tprintf (TEXT("The first file found is %s\n"), FindFileData.cFileName); FindClose(hFind); } }
上記のmsdnページのソースコード。
1つの機能で十分です。サードパーティライブラリ(Windows用)を使用する必要はありません。
#include <Windows.h>
vector<string> get_all_files_names_within_folder(string folder)
{
vector<string> names;
string search_path = folder + "/*.*";
WIN32_FIND_DATA fd;
HANDLE hFind = ::FindFirstFile(search_path.c_str(), &fd);
if(hFind != INVALID_HANDLE_VALUE) {
do {
// read all (real) files in current folder
// , delete '!' read other 2 default folder . and ..
if(! (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ) {
names.push_back(fd.cFileName);
}
}while(::FindNextFile(hFind, &fd));
::FindClose(hFind);
}
return names;
}
PS:@Sebastianが述べたように、*.*
を*.ext
に変更して、そのディレクトリのEXTファイル(つまり特定のタイプ)のみを取得できます。
Cのみのソリューションについては、こちらをご覧ください。追加のヘッダーのみが必要です:
https://github.com/cxong/tinydir
tinydir_dir dir;
tinydir_open(&dir, "/path/to/dir");
while (dir.has_next)
{
tinydir_file file;
tinydir_readfile(&dir, &file);
printf("%s", file.name);
if (file.is_dir)
{
printf("/");
}
printf("\n");
tinydir_next(&dir);
}
tinydir_close(&dir);
他のオプションに対するいくつかの利点:
- ポータブル-POSIX direntとWindows FindFirstFileをラップします
- 利用可能な場合は
readdir_r
を使用します。つまり、(通常)スレッドセーフです - 同じ
UNICODE
マクロを介してWindows UTF-16をサポート - C90なので、非常に古いコンパイラでも使用できます
この再利用可能なラッパーでglob
を使用することをお勧めします。 globパターンに適合するファイルパスに対応するvector<string>
を生成します:
#include <glob.h>
#include <vector>
using std::vector;
vector<string> globVector(const string& pattern){
glob_t glob_result;
glob(pattern.c_str(),GLOB_TILDE,NULL,&glob_result);
vector<string> files;
for(unsigned int i=0;i<glob_result.gl_pathc;++i){
files.push_back(string(glob_result.gl_pathv[i]));
}
globfree(&glob_result);
return files;
}
次に、次のような通常のシステムワイルドカードパターンで呼び出すことができます。
vector<string> files = globVector("./*");
ディレクトリ内のファイル名(フォルダ名を除く)を取得するためにC++11
ライブラリを使用するboost::filesystem
の非常に簡単なコードを次に示します。
#include <string>
#include <iostream>
#include <boost/filesystem.hpp>
using namespace std;
using namespace boost::filesystem;
int main()
{
path p("D:/AnyFolder");
for (auto i = directory_iterator(p); i != directory_iterator(); i++)
{
if (!is_directory(i->path())) //we eliminate directories
{
cout << i->path().filename().string() << endl;
}
else
continue;
}
}
出力は次のようになります:
file1.txt
file2.dat
glob()
を使用しない理由
#include <glob.h>
glob_t glob_result;
glob("/your_directory/*",GLOB_TILDE,NULL,&glob_result);
for(unsigned int i=0; i<glob_result.gl_pathc; ++i){
cout << glob_result.gl_pathv[i] << endl;
}
以下のスニペットを使用して、すべてのファイルを一覧表示できると思います。
#include <stdio.h>
#include <dirent.h>
#include <sys/types.h>
static void list_dir(const char *path)
{
struct dirent *entry;
DIR *dir = opendir(path);
if (dir == NULL) {
return;
}
while ((entry = readdir(dir)) != NULL) {
printf("%s\n",entry->d_name);
}
closedir(dir);
}
次は構造direntの構造です
struct dirent {
ino_t d_ino; /* inode number */
off_t d_off; /* offset to the next dirent */
unsigned short d_reclen; /* length of this record */
unsigned char d_type; /* type of file */
char d_name[256]; /* filename */
};
x-platformメソッドのブーストを試す
http://www.boost.org/ doc / libs / 1_38_0 / libs / filesystem / doc / index.htm
またはOS固有のファイルを使用します。
win32 APIを使用するこのクラスをチェックアウトします。リストを取得するfoldername
を指定してインスタンスを作成し、getNextFile
メソッドを呼び出してディレクトリから次のfilename
を取得します。 windows.h
とstdio.h
が必要だと思います。
class FileGetter{
WIN32_FIND_DATAA found;
HANDLE hfind;
char folderstar[255];
int chk;
public:
FileGetter(char* folder){
sprintf(folderstar,"%s\\*.*",folder);
hfind = FindFirstFileA(folderstar,&found);
//skip .
FindNextFileA(hfind,&found);
}
int getNextFile(char* fname){
//skips .. when called for the first time
chk=FindNextFileA(hfind,&found);
if (chk)
strcpy(fname, found.cFileName);
return chk;
}
};
GNUマニュアルFTW
また、ソースに直接行くのが良い場合もあります(意図したしゃれ)。 Linuxで最も一般的なコマンドのいくつかの内部を見ると、多くを学ぶことができます。 GNUのcoreutilsの単純なミラーをgithubにセットアップしました(読み取り用)。
https://github.com/homer6/gnu_coreutils/blob/master/src/ls .c
これはWindowsに対応していないかもしれませんが、これらの方法を使用することで、Unixバリアントを使用する多くのケースが発生する可能性があります。
役立つこと...
char **getKeys(char *data_dir, char* tablename, int *num_keys)
{
char** arr = malloc(MAX_RECORDS_PER_TABLE*sizeof(char*));
int i = 0;
for (;i < MAX_RECORDS_PER_TABLE; i++)
arr[i] = malloc( (MAX_KEY_LEN+1) * sizeof(char) );
char *buf = (char *)malloc( (MAX_KEY_LEN+1)*sizeof(char) );
snprintf(buf, MAX_KEY_LEN+1, "%s/%s", data_dir, tablename);
DIR* tableDir = opendir(buf);
struct dirent* getInfo;
readdir(tableDir); // ignore '.'
readdir(tableDir); // ignore '..'
i = 0;
while(1)
{
getInfo = readdir(tableDir);
if (getInfo == 0)
break;
strcpy(arr[i++], getInfo->d_name);
}
*(num_keys) = i;
return arr;
}
このコードがお役に立てば幸いです。
#include <windows.h>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
string wchar_t2string(const wchar_t *wchar)
{
string str = "";
int index = 0;
while(wchar[index] != 0)
{
str += (char)wchar[index];
++index;
}
return str;
}
wchar_t *string2wchar_t(const string &str)
{
wchar_t wchar[260];
int index = 0;
while(index < str.size())
{
wchar[index] = (wchar_t)str[index];
++index;
}
wchar[index] = 0;
return wchar;
}
vector<string> listFilesInDirectory(string directoryName)
{
WIN32_FIND_DATA FindFileData;
wchar_t * FileName = string2wchar_t(directoryName);
HANDLE hFind = FindFirstFile(FileName, &FindFileData);
vector<string> listFileNames;
listFileNames.push_back(wchar_t2string(FindFileData.cFileName));
while (FindNextFile(hFind, &FindFileData))
listFileNames.push_back(wchar_t2string(FindFileData.cFileName));
return listFileNames;
}
void main()
{
vector<string> listFiles;
listFiles = listFilesInDirectory("C:\\*.txt");
for each (string str in listFiles)
cout << str << endl;
}
Shreevardhanの回答はすばらしい。ただし、C ++ 14で使用する場合は、変更を加えてくださいnamespace fs = experimental::filesystem;
i.e。、
#include <string>
#include <iostream>
#include <filesystem>
using namespace std;
namespace fs = experimental::filesystem;
int main()
{
string path = "C:\\splits\\";
for (auto & p : fs::directory_iterator(path))
cout << p << endl;
int n;
cin >> n;
}
この実装は目的を実現し、文字列の配列を指定されたディレクトリのコンテンツで動的に埋めます。
int exploreDirectory(const char *dirpath, char ***list, int *numItems) {
struct dirent **direntList;
int i;
errno = 0;
if ((*numItems = scandir(dirpath, &direntList, NULL, alphasort)) == -1)
return errno;
if (!((*list) = malloc(sizeof(char *) * (*numItems)))) {
fprintf(stderr, "Error in list allocation for file list: dirpath=%s.\n", dirpath);
exit(EXIT_FAILURE);
}
for (i = 0; i < *numItems; i++) {
(*list)[i] = stringDuplication(direntList[i]->d_name);
}
for (i = 0; i < *numItems; i++) {
free(direntList[i]);
}
free(direntList);
return 0;
}
これは私には有効です。ソースを思い出せない場合は申し訳ありません。おそらくmanページからです。
#include <ftw.h>
int AnalizeDirectoryElement (const char *fpath,
const struct stat *sb,
int tflag,
struct FTW *ftwbuf) {
if (tflag == FTW_F) {
std::string strFileName(fpath);
DoSomethingWith(strFileName);
}
return 0;
}
void WalkDirectoryTree (const char * pchFileName) {
int nFlags = 0;
if (nftw(pchFileName, AnalizeDirectoryElement, 20, nFlags) == -1) {
perror("nftw");
}
}
int main() {
WalkDirectoryTree("some_dir/");
}
std :: experimental :: filesystem :: directory_iterator()を使用して、ルートディレクトリ内のすべてのファイルを直接取得できます。次に、これらのパスファイルの名前を読み取ります。
#include <iostream>
#include <filesystem>
#include <string>
#include <direct.h>
using namespace std;
namespace fs = std::experimental::filesystem;
void ShowListFile(string path)
{
for(auto &p: fs::directory_iterator(path)) /*get directory */
cout<<p.path().filename()<<endl; // get file name
}
int main() {
ShowListFile("C:/Users/dell/Pictures/Camera Roll/");
getchar();
return 0;
}
システムコール!
system( "dir /b /s /a-d * > file_names.txt" );
その後、ファイルを読み取ります。
編集:この回答はハックと見なされるべきですが、よりエレガントなソリューションにアクセスできない場合は(プラットフォーム固有の方法ではありますが)実際に機能します。
ディレクトリのファイルとサブディレクトリは一般にツリー構造で保存されるため、直観的な方法は、DFSアルゴリズムを使用してそれぞれを再帰的に走査することです。 io.hの基本的なファイル関数を使用したWindowsオペレーティングシステムの例を次に示します。これらの機能は他のプラットフォームで置き換えることができます。私が言いたいのは、DFSの基本的な考え方がこの問題を完全に満たしているということです。
#include<io.h>
#include<iostream.h>
#include<string>
using namespace std;
void TraverseFilesUsingDFS(const string& folder_path){
_finddata_t file_info;
string any_file_pattern = folder_path + "\\*";
intptr_t handle = _findfirst(any_file_pattern.c_str(),&file_info);
//If folder_path exsist, using any_file_pattern will find at least two files "." and "..",
//of which "." means current dir and ".." means parent dir
if (handle == -1){
cerr << "folder path not exist: " << folder_path << endl;
exit(-1);
}
//iteratively check each file or sub_directory in current folder
do{
string file_name=file_info.name; //from char array to string
//check whtether it is a sub direcotry or a file
if (file_info.attrib & _A_SUBDIR){
if (file_name != "." && file_name != ".."){
string sub_folder_path = folder_path + "\\" + file_name;
TraverseFilesUsingDFS(sub_folder_path);
cout << "a sub_folder path: " << sub_folder_path << endl;
}
}
else
cout << "file name: " << file_name << endl;
} while (_findnext(handle, &file_info) == 0);
//
_findclose(handle);
}
この回答は、他の回答のいずれかを使用してVisual Studioでこれを動作させるのに問題があったWindowsユーザーに対して機能するはずです。
-
githubページからdirent.hファイルをダウンロードします。ただし、Raw dirent.hファイルを使用して、以下の手順に従うことをお勧めします(動作させる方法です)。
Windows用dirent.hのGithubページ: direntのGithubページ.h
Raw Direntファイル: Raw dirent.hファイル
-
プロジェクトに移動して、新しいアイテムを追加します( Ctrl + Shift + A )。ヘッダーファイル(.h)を追加し、dirent.hという名前を付けます。
-
生dirent.hファイルヘッダーにコーディングします。
-
<!> quot; dirent.h <!> quotを含める;コードで。
-
以下の
void filefinder()
メソッドをコードに追加し、main
関数から呼び出すか、使用方法を編集します。#include <stdio.h> #include <string.h> #include "dirent.h" string path = "C:/folder"; //Put a valid path here for folder void filefinder() { DIR *directory = opendir(path.c_str()); struct dirent *direntStruct; if (directory != NULL) { while (direntStruct = readdir(directory)) { printf("File Name: %s\n", direntStruct->d_name); //If you are using <stdio.h> //std::cout << direntStruct->d_name << std::endl; //If you are using <iostream> } } closedir(directory); }
両方に記載されている例に従うことを試みました回答があり、std::filesystem::directory_entry
が<<
演算子のオーバーロードを持たないように変更されているように見えることに注意してください。 std::cout << p << std::endl;
の代わりに、以下を使用してコンパイルし、機能させる必要がありました。
#include <iostream>
#include <filesystem>
#include <string>
namespace fs = std::filesystem;
int main() {
std::string path = "/path/to/directory";
for(const auto& p : fs::directory_iterator(path))
std::cout << p.path() << std::endl;
}
p
を単独でstd::cout <<
に渡そうとすると、オーバーロードエラーが発生します。
私が共有したいことの1つであり、読み物に感謝します。関数を少し理解して理解してください。あなたはそれを好きかもしれません。 eは拡張子を表し、pはパスを表し、sはパス区切り文字を表します。
パスが終了セパレータなしで渡される場合、セパレータがパスに追加されます。拡張子については、空の文字列が入力された場合、関数は名前に拡張子のないファイルを返します。単一の星が入力された場合、ディレクトリ内のすべてのファイルが返されます。 eの長さが0より大きいが、単一の*ではない場合、eがゼロ位置にドットを含んでいなかった場合、eの前にドットが追加されます。
戻り値用。長さゼロのマップが返された場合、ディレクトリは正常に開いていましたが、何も見つかりませんでした。戻り値からインデックス999は使用できるが、マップサイズが1だけの場合、ディレクトリパスを開くときに問題が発生したことを意味します。
効率のために、この関数は3つの小さな関数に分割できます。さらに、入力に基づいてどの関数を呼び出すかを検出する呼び出し元関数を作成できます。なぜそれが効率的ですか?ファイルであるすべてのものを取得する場合、すべてのファイルを取得するために構築されたサブ関数がそのメソッドを実行すると、ファイルであるすべてのものを取得するだけで、ファイルを見つけるたびに他の不要な条件を評価する必要はありません。
これは、拡張子のないファイルを取得する場合にも当てはまります。その目的のための特定の組み込み関数は、見つかったオブジェクトがファイルである場合にのみ天気を評価し、ファイルの名前にドットが含まれているかどうかを評価します。
ファイルがそれほど多くないディレクトリのみを読み取る場合、保存量はそれほど多くありません。しかし、大量のディレクトリを読み込んでいる場合、またはディレクトリに数十万個のファイルがある場合、大幅に節約できます。
#include <stdio.h>
#include <sys/stat.h>
#include <iostream>
#include <dirent.h>
#include <map>
std::map<int, std::string> getFile(std::string p, std::string e = "", unsigned char s = '/'){
if ( p.size() > 0 ){
if (p.back() != s) p += s;
}
if ( e.size() > 0 ){
if ( e.at(0) != '.' && !(e.size() == 1 && e.at(0) == '*') ) e = "." + e;
}
DIR *dir;
struct dirent *ent;
struct stat sb;
std::map<int, std::string> r = {{999, "FAILED"}};
std::string temp;
int f = 0;
bool fd;
if ( (dir = opendir(p.c_str())) != NULL ){
r.erase (999);
while ((ent = readdir (dir)) != NULL){
temp = ent->d_name;
fd = temp.find(".") != std::string::npos? true : false;
temp = p + temp;
if (stat(temp.c_str(), &sb) == 0 && S_ISREG(sb.st_mode)){
if ( e.size() == 1 && e.at(0) == '*' ){
r[f] = temp;
f++;
} else {
if (e.size() == 0){
if ( fd == false ){
r[f] = temp;
f++;
}
continue;
}
if (e.size() > temp.size()) continue;
if ( temp.substr(temp.size() - e.size()) == e ){
r[f] = temp;
f++;
}
}
}
}
closedir(dir);
return r;
} else {
return r;
}
}
void printMap(auto &m){
for (const auto &p : m) {
std::cout << "m[" << p.first << "] = " << p.second << std::endl;
}
}
int main(){
std::map<int, std::string> k = getFile("./", "");
printMap(k);
return 0;
}
これは私のために働いた。すべてのファイルの名前のみ(パスなし)でファイルを書き込みます。次に、そのtxtファイルを読み取り、印刷します。
void DisplayFolderContent()
{
system("dir /n /b * > file_names.txt");
char ch;
std::fstream myStream("file_names.txt", std::fstream::in);
while (myStream.get(ch))
{
std::cout << ch;
}
}