我如何读取 C++ 目录中的所有文件?
How can i read all files in directory in c++?
我想读取特定目录中的所有文件。
例如
在目录a中有file1.textfile2.txta.txtc.txt
我想知道每个文件包含多少个单词。
我为一个文件编写了一个代码。
但是我不知道如何自动移动到同一目录下的下一个文件。
int EBook::get_total_words()
{
ifstream ifs("inputs//a.txt");
int words = 0;
string word;
if (!ifs)
{
std::cout << "Unable to open file " << '\n';
exit(1);
}
while (ifs >> word) {
++words;
}
return words;
}
使用 std::filesystem
你可以这样做:
std::string path_to_dir = '/some/path/';
for( const auto & entry : std::filesystem::directory_iterator( path_to_dir ) ){
std::cout << entry.path( ) << std::endl;
}
我想读取特定目录中的所有文件。 例如 在目录a中有file1.textfile2.txta.txtc.txt
我想知道每个文件包含多少个单词。 我为一个文件编写了一个代码。 但是我不知道如何自动移动到同一目录下的下一个文件。
int EBook::get_total_words() {
ifstream ifs("inputs//a.txt");
int words = 0;
string word;
if (!ifs)
{
std::cout << "Unable to open file " << '\n';
exit(1);
}
while (ifs >> word) {
++words;
}
return words;
}
使用 std::filesystem
你可以这样做:
std::string path_to_dir = '/some/path/';
for( const auto & entry : std::filesystem::directory_iterator( path_to_dir ) ){
std::cout << entry.path( ) << std::endl;
}