读取和写入许多文本文件
Read and write many text files
我在一个文件夹中有100个文件。我是否可以自动读取所有文件并将其写入其他文本文件?否则我必须手动输入路径。如果可能的话,我应该使用什么函数?或者我应该在函数中包含counter ?下面是我打开和写入文件的方式:
using namespace std;
string filename;
string line;
ofstream fout("text1.txt") ;
void path_enter(){
cout<<"Please enter the path of your filen";
cin>>filename;
ifstream fin(filename.c_str());
int i=1;
if (!fin)
{
cout<<"failedn";
}
else
{
while (getline(fin,line,'.')){
cout<<"nLine"<<i<<" : "<<line<<endl<<endl;
fout<<"nLine"<<i<<" : "<<line<<endl<<endl;
i++;
}
}
fin.close();
}
可以在这里列出某个目录下的所有文件。所以我建议如下:
- 获取该目录下所有文件的列表。
- 遍历该列表以读取
- 最后,对于你的输出,你可以在你读取的文件后面附加一个字符串。
为了更好地区分输入文件和输出文件,我将输出文件保存到另一个目录。
下面的代码将返回给定目录中所有文件的列表。
#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;
}
相关文章:
- 文本文件中的单词链表
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 如何将内容数组写入文本文件?
- 无法通过空白将文本文件行分隔为矢量
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- C++将文本文件中的数据读取到结构数组中
- 在指针的帮助下,文本文件中单词的频率
- 将字符指针十六进制转换为字符串并保存在文本文件C++中
- 将值从二维数组输出到文本文件
- 如何在c++中从文本文件中逐行读取整数
- 从文本文件中读取时钟时间和事件时间并进行处理
- 如何从文本文件中读取值和数组
- 如何在C++中确定文本文件中的元素是字符还是数字
- C++试图读取一个文件并输出到另一个文本文件
- 如何通过套接字将文本文件的内容从服务器发送到客户端
- 已修改的LinkedList未在文本文件本身中更新
- C++文本文件的获取线
- 为什么C++的文件 I/O 在读取文本文件时忽略初始空行?我怎样才能让它不这样做?
- 打印逐行存储的文本文件
- C++文本文件输入