如何从文件夹中读取所有txt文件?(包括子文件夹)

How to read all txt files from a folder? (including subfolders)

本文关键字:文件夹 文件 包括 txt 读取      更新时间:2023-10-16

我正在尝试使用C++读取文件夹中的所有txt文件,包括所选文件夹子目录中的txt文件。

我实现了该程序的一个版本,它从特定文件夹中读取所有文本文件,但不迭代到所有子文件夹。

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <iterator>
#include <string>
#include <dirent.h>
using namespace std;
int main() {
    DIR*     dir;
    dirent*  pdir;
    dir = opendir("D:/");     // open current directory
    int number_of_words=0;
    int text_length = 30;
    char filename[300];
    while (pdir = readdir(dir)) 
    {
        cout << pdir->d_name << endl;
        strcpy(filename, "D:/...");
        strcat(filename, pdir->d_name);
        ifstream file(filename);
        std::istream_iterator<std::string> beg(file), end;
        number_of_words = distance(beg,end);
        cout<<"Number of words in file: "<<number_of_words<<endl;
        ifstream files(filename);
        char output[30];
        if (file.is_open()) 
        {
            while (!files.eof())
            {
                    files >> output;
                    cout<<output<<endl;
            }
        }
        file.close();
    }
    closedir(dir);
    return 0;
}

为了在所选文件夹的子文件夹中搜索txt文件,我应该对此程序进行什么修改?

最简单的方法是编写一个read_one_file()函数,并递归调用它。

read_one_file()看起来像这样:

read_one_file(string filename){
    if(/* this file is a directory */){
        opendir(filename);
        while(entry=readdir){
            read_one_file(/*entry's filename*/);
        }
    }else{ /* this file is a regular file */
        /* output the file */
    }
}

我在这里找到了一种检查文件是否是目录的方法:访问C 中的目录

首先应该做的是将代码放入一个函数中,比如说void f(char*dir),这样就可以处理多个文件夹。然后使用上面链接中提供的代码来查找文件是否为目录。

如果它是一个目录,调用f,如果它是txt文件,做你想做的事

注意一件事:在每个目录中都有一些目录会将您发送到一个无限循环。"."指向当前目录,".."指向父目录,"~"指向主目录。你可能会想排除这些。http://en.wikipedia.org/wiki/Path_%28computing%29