C++中的文件全局

nev*_*int 9 c++ perl glob file

Perl成语的C++方式是什么:

my @files = glob("file*.txt");
foreach my $file (@files) {

   # process $file
}
Run Code Online (Sandbox Code Playgroud)

Ken*_*oom 18

POSIX API 为此指定了函数glob()globfree()函数.请参见手册页.wordexp()并且wordfree(),也由POSIX指定,也支持其他类型的扩展.


wil*_*ell 7

没有标准的C++方法来模拟这个,因为没有标准的C++功能来读取目录的内容.你可以做的是使用Boost.Filesystem:

#include <boost/filesystem.hpp> // plus iostream,algorithm,string,iterator
using namespace boost::filesystem; // and std

struct pathname_of {
    string operator()(const directory_entry& p) const {
        return p.path().filename(); // or your creativity here
    }
};

int main(int argc, char* argv[])
{
    transform(directory_iterator("."), directory_iterator(),
              ostream_iterator<string>(cout, "\n"),
              pathname_of());
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

  • 是否有任何提升无法做到的?!?! (2认同)
  • 你得到什么错误?编译器,链接器?确保添加缺少的include:`<algorithm>`.说`std :: for_each()`或添加`using`语句.你在Linux或Mac上吗?如果您使用的是Linux,请确保链接到"boost_filesystem".使用g ++,你可以说`-lboost_filesystem`.如果你在Mac上,你可能还需要链接`boost_system`. (2认同)