打开向量数组的每个文件,使用LineCount函数计数每个文件中的行数
Open every file of the vector array, count the number of lines in each file using lineCount function
我需要打开一个由用户输入的指定目录,打开该文件夹目录的每个文件,计算每个文件的行数,然后最后完成所有行的总和该文件夹中的所有文件。因此,基本上,我成功打开目录并将所有文件名放在向量数组中。所以我做到了:
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
有两个问题:
-
open()
的第一个参数期望const char *
-您给它一个string
。
使用fn.c_str()
- 第二个参数说要打开
in
和out
的文件 - 但是您只会阅读它。
删除| std::fstream::out
。
并且不要忘记:所有传递给lineCount()
函数的所有内容都是文件的名称:实际目录仍需要将其固定在文件的名称中。我不知道您称之为什么 - 或目录在其末尾具有路径分离器(''
或'/'
) - 但是您基本上需要这样做:
fn = dir + fn;
尝试打开文件之前。
相关文章:
- C++ gmock - 我们如何在单元测试 cpp 文件中读取/获取 cpp 文件函数的参数值
- 使用其他头文件函数的头文件
- 创建文件函数是否可以打开仅在WinObj实用程序中的全局目录下列出的设备的句柄?
- 如何指定创建文件函数获取未缓存的结果?
- 标准库头文件函数原型的实现是如何用 c++ 编写的?
- 如何将类对象作为对另一个头文件函数的引用传递
- 读取文件函数lpbuffer和字节以读取澄清
- C++ - 未定义的对多个文件函数的引用
- 使用C++的可视 Unicode 文件函数
- C 创建文件函数错误
- WinAPI 创建文件函数 2.
- 具有CREATE_ALWAYS处置的创建文件函数
- 重写c库文件函数
- 如何使用客户端调用堆栈中的地址从 PDB 检索文件/函数/行号?
- 通过头文件函数将遍历的数据从二进制搜索树加载到Vector中
- 需要帮助无法弄清楚为什么我的头文件函数声明不起作用
- 是否可以在不使用文件函数的情况下使用代码块从文件运行某些用例测试?
- 如何用c++文件函数读写8位整数单位形式的数据
- 在c++中读文件函数如何识别文本文件的结束
- 使用Windows API的c++文件函数