编辑和删除文件C / C ++中的数据 [英] Edit and delete data in file C/C++
问题描述
Hellow!
我想在文件(C / C ++)中编辑和删除数据。< br $> b $ b
我尝试了什么:
我试过这种方法
ifstream read,read1;
ofstream write,write1;
read.open( File.txt,ios :: < span class =code-keyword> in );
write.open( Temp.txt);
int old,New,a;
cout<< 输入您要编辑的编号=;
cin>>旧;
cout<< 输入要替换的新号码;
cin>>新;
while (!read.eof()){
read>>一个;
if (a == old){write<<新<< ENDL; }
else {write<< a<< ENDL; }
}
read.close();
write.close();
read1.open( Temp.txt,ios :: app );
write1.open( File.txt);
while (!read1.eof()){
read1>>一个;
write1<< a<< ENDL;
}
此代码运作良好。
但问题是这个过程很慢。我的意思是如果文件中有数千行,我想编辑或删除一行,那么过程非常慢。
所以我需要一些算法,我可以编辑或删除只是我想要的那条线。
那么有没有算法或函数?
谢谢!
您可以避免仅复制内容的第二个while循环。而是删除 File.txt ,然后重命名 Temp.txt :
// 只有使用过的C库
// <才需要删除文件/ span> 实现不支持重命名为现有文件
remove( file.txt的跨度>);
重命名( Temp.txt, File.txt);这将使您的应用程序运行大约一半的大型文件代码。
我会做以下事情:
1)以字符串形式阅读完整文件
2 )制作比字符串替换
3)并写入文件
使用std :: string来支持我的计划; - )
Hellow!
I want to edit and delete data in file(C/C++).
What I have tried:
I have tried this method
ifstream read, read1;
ofstream write, write1;
read.open("File.txt", ios::in);
write.open("Temp.txt");
int old, New, a;
cout << "Enter number you want to edit = ";
cin >> old;
cout << "Enter new number to replace ";
cin >> New;
while (!read.eof()) {
read >> a;
if (a == old) { write << New << endl; }
else { write << a << endl; }
}
read.close();
write.close();
read1.open("Temp.txt", ios::app);
write1.open("File.txt");
while (!read1.eof()) {
read1 >> a;
write1 << a << endl;
}
And this code work well.
But the issue is that this process is very slow. I mean if there are thousand of lines in file and i want to edit or delete just one line then the process is very slow.
So i need some algorithm by using that i can able to edit or delete just that line i want.
So is there any algorithm or Function?
Thanks!
You can avoid the second while loop which is just copying the content. Instead delete File.txt and then rename Temp.txt:
// Deleting the file is only necessary if the used C library // implementation does not support renaming to an existing file remove("File.txt"); rename("Temp.txt", "File.txt");That will make your application run about half the time of your code with large files.
I would do the following:
1) read the full file in a string
2) make than a string replace
3) and write the file
use std::string for supporting my plan ;-)
这篇关于编辑和删除文件C / C ++中的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!