【问题标题】:How to read all txt files from a folder? (including subfolders) [duplicate]如何从文件夹中读取所有txt文件? (包括子文件夹)[重复]
【发布时间】:2014-10-17 08:41:31
【问题描述】:

我正在尝试从一个文件夹中读取所有 txt 文件,包括使用 C++ 从所选文件夹的子目录中读取的 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文件?

【问题讨论】:

标签: c++ io


【解决方案1】:

最简单的方法是写一个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 */
    }
}

【讨论】:

【解决方案2】:

我在这里找到了一种检查文件是否为目录的方法:Accessing Directories in C

您应该首先将代码放入一个函数中,例如 void f(char *dir),以便您可以处理多个文件夹。然后使用上面链接中提供的代码来判断一个文件是否是一个目录。

如果是目录,就调用 f ,如果是 txt 文件,做你想做的。

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

猜你喜欢
  • 2018-06-06
  • 2011-02-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-20
  • 2017-07-05
  • 1970-01-01
相关资源
最近更新 更多