c++修改或者删除txt中内容的某一行&c++:删除txt文件内容中的某一行(有100个文件,需要批量执行)
(2013-11-14 15:14:42)| 分类: cpp |
c++修改或者删除txt中内容的某一行&c++:删除txt文件内容中的某一行(有100个文件,需要批量执行)
下面是实现你输入行数,删除对应行
主要思想就是新开一个文件,保存除了你要删除行的其它行的数据,再存回原文件
再删除这个中间新开的文件,修改内容就简单了
#include
#include
#include
#include
#include
using namespace std;
void main()
{
fstream file("in.txt");
string line;
int n,count=0;
ofstream outfile("in2.txt",ios::out|ios::trunc);
cout<<"Please input the line number you want to del:"<<endl;
cin>>n;
while(!file.eof())
{
getline(file,line);
if(count!=n-1)//如果要修改内容就在这修改line的内容,再存到文件中就行了
outfile<<line<<endl;
count++;
}
outfile.close();
file.close();
ofstream outfile1("in.txt",ios::out|ios::trunc);
fstream file1("in2.txt");
while(!file1.eof())
{
getline(file1,line);
outfile1<<line<<endl;
}
outfile1.close();
file1.close();
system("del in2.txt");//删除中间文件
}
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
string itos(int i)
{
ostringstream str;
str << i;
return str.str();
}
int main()
{
int n;
cout<<"Please input the line number you want to del:"<<endl;
cin>>n;
char openname[20]; //存名字。
char savename[20]; //存名字。
for(int i = 1; i <= 100;++i)
{
strcpy(openname,"newfile-");
char open[255];
sprintf(open,"%d",i);
strcat(openname,open); //添加数字
strcat(openname,".txt"); //添加后缀
strcpy(savename,"cut-newfile-");
char save[255];
sprintf(save,"%d",i);
strcat(savename,save); //添加数字
strcat(savename,".txt"); //添加后缀
//string openname = "E://newfile-" + itoa(i)+".txt"; //我这边测试的在E盘 你自己修改文件保存路径
//string savename = "E://cut-newfile-"+ itoa(i)+".txt"; // windows 下面运行
fstream file(openname);
ofstream outfile(savename,ios::out|ios::trunc);
int count = 0;
while(!file.eof())
{
string line;
getline(file,line);
if(count != n-1)
outfile << line << endl;
count++;
}
outfile.close();
file.close();
}
}
注:Ubuntu下的C++与windows下的C++不同之处:strcpy()与 itos()
另附链接:http://zhidao.baidu.com/link?url=Q1zS7n8R4xrCmE6lR6Zm7L7TCUnjiffzaxtjny-huCUoU2Hz7izegoQxfMCNnYH fnzQF_B6byVjWsf10diGzcK&autorefresh=1384309474043
http://zhidao.baidu.com/question/1638109436459674260.html?quesup2&oldq=1

加载中…