打开向量数组的每个文件,使用LineCount函数计数每个文件中的行数

Open every file of the vector array, count the number of lines in each file using lineCount function

本文关键字:文件 函数 LineCount 向量 使用 数组      更新时间:2023-10-16

我需要打开一个由用户输入的指定目录,打开该文件夹目录的每个文件,计算每个文件的行数,然后最后完成所有行的总和该文件夹中的所有文件。因此,基本上,我成功打开目录并将所有文件名放在向量数组中。所以我做到了:

vector < string > dirlist;
dirlist.push_back(ent->d_name) //To add file names in the vector array

名称在向量数组中成功推动,我能够显示它。

,但现在我想使用for_each将lineCount函数应用于向量数组的每个元素,我不能:

for_each (dirlist.begin(),dirlist.end(), lineCount);

linecount功能:

void lineCount (string fn)
{ 
    ifstream fileInput;
    string line;
    int number_of_lines = 0;  //initialise number_of_lines to 0
    fileInput.open(fn.c_str(), std::fstream::in); //open file
    if(fileInput.is_open()) {  //test if file is opened
            while(getline(fileInput, line)) {
                ++number_of_lines;
            }
            cout << "Number of lines in file: " << number_of_lines;
            fileInput.close();
    }
    else cout <<"Unable to Open File"<<endl;
}

现在,我无法为目录中的每个文件打开

fileInput.open(fn, std::fstream::in | std::fstream::out); //open file

有两个问题:

  1. open()的第一个参数期望const char *-您给它一个string
    使用fn.c_str()
  2. 第二个参数说要打开 inout的文件 - 但是您只会阅读它。
    删除| std::fstream::out

并且不要忘记:所有传递给lineCount()函数的所有内容都是文件的名称:实际目录仍需要将其固定在文件的名称中。我不知道您称之为什么 - 或目录在其末尾具有路径分离器('''/') - 但是您基本上需要这样做:

fn = dir + fn;

尝试打开文件之前。