我在一个文件夹中有100个文件。我可以自动读取所有文件并将其写入其他文本文件吗?否则我必须手动键入路径。如果可能,我应该使用哪些功能?或者我应该在我的功能中包含计数器?这就是我打开和写入文件的方式:
using namespace std;
string filename;
string line;
ofstream fout("text1.txt") ;
void path_enter(){
cout<<"Please enter the path of your file\n";
cin>>filename;
ifstream fin(filename.c_str());
int i=1;
if (!fin)
{
cout<<"failed\n";
}
else
{
while (getline(fin,line,'.')){
cout<<"\nLine"<<i<<" : "<<line<<endl<<endl;
fout<<"\nLine"<<i<<" : "<<line<<endl<<endl;
i++;
}
}
fin.close();
}
答案 0 :(得分:1)
可以列出某个目录see here的所有文件。所以我建议如下:
为了更好地区分输入和输出文件,我将输出文件保存到另一个目录。
以下代码将返回给定目录中所有文件的列表。
#include <stdio.h>
#include <cstdlib>
#include <iostream>
#include <string>
#include <fstream>
#include <dirent.h>
#include <vector>
#include <cstring>
/*
* @Ipath path to directory
* @relative true, if the path is a relative path, else false
*/
vector<string> getFiles(string Ipath, bool relative){
vector<string> list; //the list that should be returned
if(relative) //edit the path, if it is relative
Ipath = "./" + Ipath;
//convert the path from string to char*
char* path = new char[Ipath.length()];
strcpy(path, Ipath.c_str());
//initialize the DIR
DIR *pDIR;
struct dirent *entry;
if( pDIR=opendir(path) ){ //check if the path exists, if yes open
//as long as there is a file left, we didn't look at do
while(entry = readdir(pDIR)){
//check if the filename is a valid filename
if( strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0 ){
string fE(entry->d_name); //convert the char* to string
list.push_back(entry->d_name); //add the string to the list
}
}
closedir(pDIR);
}
return list;
}