次のコードを使用して、共有ドライブの特定のディレクトリにあるすべてのファイルを一覧表示しようとしています:
#include <iostream>
#include <string>
#include "dirent.h"
int main ()
{
DIR *directoryHandle = opendir("./temp/");
if (NULL != directoryHandle)
{
dirent *entry = readdir(directoryHandle);
while (NULL != entry)
{
//skip directories and select only files (hopefully)
if ((DT_DIR != entry->d_type) && (DT_REG == entry->d_type || DT_UNKNOWN == entry->d_type))
{
std::cout << "Name: " << entry->d_name << " Type:" << std::to_string(entry->d_type) << std::endl;
}
//go to next entry
entry = readdir(directoryHandle);
}
closedir(directoryHandle);
}
return 0;
}
問題は、entry->d_type にディレクトリとディレクトリ内のファイルの DT_UNKNOWN が含まれていることです./temp/
。
各エントリを試して読み取って、それがファイルかディレクトリかを判断する (信頼できる) Linux 固有の方法はありますか?
の出力cat /etc/SuSE-release
は次のとおりです。
SUSE Linux Enterprise Desktop 11 (x86_64) バージョン = 11 パッチレベル = 1
Linux のバージョンは次のとおりです: 2.6.32.59-0.7-default
それでも、このコードは他のプラットフォームでも機能すると思います。