我需要打开用户输入的指定目录,打开该文件夹目录的每个文件,计算每个文件的行数,然后最后完成该文件夹中所有文件的所有行的总和。所以基本上我成功打开目录并将所有文件名放在矢量数组中。所以我做了:
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;
}
现在我无法打开目录中的每个文件
答案 0 :(得分:0)
该行
fileInput.open(fn, std::fstream::in | std::fstream::out); //open file
有两个问题:
open()
的第一个参数需要const char *
- 你给它一个string
。fn.c_str()
in
和out
的文件 - 但您只会阅读它。| std::fstream::out
。不要忘记:您传递给lineCount()
函数的所有内容都是文件的名称:实际目录仍需要添加到文件名前面。我不知道你叫它什么 - 或者如果目录在它的末尾有一个路径分隔符('\'
或'/'
) - 但你基本上需要这样做:
fn = dir + fn;
在尝试打开文件之前。