ファイルが通常のファイルであるかどうかを確認するにはどうすればよいですか?

StackOverflow https://stackoverflow.com/questions/328944

  •  11-07-2019
  •  | 
  •  

質問

ファイルが通常のファイル(ディレクトリ、パイプなどではない)である場合、C ++でチェックインするにはどうすればよいですか?関数isFile()が必要です。

DIR *dp;
struct dirent *dirp;

while ((dirp = readdir(dp)) != NULL) {
if ( isFile(dirp)) {
     cout << "IS A FILE!" << endl;
i++;
}

dirp-&gt; d_typeと(unsigned char)0x8を比較しようとしましたが、異なるシステムを介して移植できないようです。

役に立ちましたか?

解決

ファイルでstat(2)を呼び出してから、st_modeでS_ISREGマクロを使用する必要があります。

次のようなもの(この回答から適応):

#include <sys/stat.h>

struct stat sb;

if (stat(pathname, &sb) == 0 && S_ISREG(sb.st_mode))
{
    // file exists and it's a regular file
}

他のヒント

ポータブル boostを使用できます。 :: filesystem (標準C ++ライブラリは、最近 C ++ 17のstd :: filesystem ):

#include <boost/filesystem/path.hpp>
#include <boost/filesystem/operations.hpp>
#include <iostream>

int main() {
    using namespace boost::filesystem;

    path p("/bin/bash");
    if(is_regular_file(p)) {
        std::cout << "exists and is regular file" << std::endl;
    }
}

C ++自体はファイルシステムを処理しないため、言語自体に移植可能な方法はありません。プラットフォーム固有の例は、* nixの stat (Martin v。L&#246; wisで既に述べたとおり)およびWindowsの GetFileAttributes です。

また、ブーストにアレルギーがない場合は、かなりクロスプラットフォームな boostがあります::ファイルシステム

C ++ 17では、std :: filesystem :: is_regular_fileを使用できます

#include <filesystem> // additional include

if(std::filesystem::is_regular_file(yourFilePathToCheck)) 
    ; //Do what you need to do

C ++の以前のバージョンでは、std :: experimental :: filesystemの下にあった可能性があることに注意してください(ソース: http://en.cppreference.com/w/cpp/filesystem/is_regular_file

助けてくれてありがとう、私は試しました

while ((dirp = readdir(dp)) != NULL) { 
   if (!S_ISDIR(dirp->d_type)) { 
        ... 
        i++; 
   } 
} 

そしてそれは正常に動作します。 =)

#include <boost/filesystem.hpp>

bool isFile(std::string filepath)
{
    boost::filesystem::path p(filepath);
    if(boost::filesystem::is_regular_file(p)) {
        return true;
    }
    std::cout<<filepath<<" file does not exist and is not a regular file"<<std::endl;
    return false;
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top