要做一个通讯录系统,我用了txt文件来存取数据,但是在删除功能上,能做到把第一个文件的内容提到第二个文件,但是无法输回去,
请问该如何解决?问题在哪?
还有我使用的是getline函数,一次只能删除一行,如何改进来做到连续删除几行?
代码如下
看下面这个小程序你大概就可以知道是怎么回事了.
首先,你应当建立一个文件夹,然后把你的程序以及记事本文件全部装入,值得注意的地方是文件夹中的txt文件的末尾没有.txt的后缀,但是在程序中读取的时候就得用上了,下面是假装你的记事本文档的名字叫做book的时候对book里面的内容进行读取的代码:
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
fstream ifs;
ifs.open("book.txt",ios::in);
//注意,这个时候就必须要写.txt的后缀了.
string str;
while(getline(ifs,str))
{
//这个循环会把book里面的内容逐行逐行地读取出来.
//并且当文件读完的时候,就会从循环里面退出.
//可以试一下读进再输出的操作.
cout<<str<<endl;
//然后你就会发现,这个程序确实可以运行.
//不过往记事本里面塞中文,会出来乱码.
//不过哈利波特似乎里面没有中文.
//并没有什么关系.
}
ifs.close();//格式.这一行并不可以省略.
}
针对删除功能无法将修改后的内容写回到原文件的问题,可以使用一个临时文件来存储修改后的内容,待修改完成后再将临时文件的内容覆盖原文件。具体步骤如下:
示例代码如下:
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
int main()
{
string filename = "contacts.txt";
string tempfilename = "temp.txt";
ifstream ifs(filename);
ofstream ofs(tempfilename);
if (!ifs) {
cerr << "Error opening file " << filename << endl;
exit(EXIT_FAILURE);
}
if (!ofs) {
cerr << "Error creating temp file " << tempfilename << endl;
exit(EXIT_FAILURE);
}
string line;
while (getline(ifs, line)) {
// 如果该行需要删除则跳过
if (line.find("delete_this_line") != string::npos) {
continue;
}
// 其他行则写入临时文件
ofs << line << endl;
}
ifs.close();
ofs.close();
// 删除原文件并更名临时文件
remove(filename.c_str());
rename(tempfilename.c_str(), filename.c_str());
return 0;
}
针对连续删除多行的问题,可以使用一个标记变量来表示当前是否需要删除该行,每读取一行就判断该标记变量是否为true,如为true则跳过该行,否则继续执行操作。示例代码如下:
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
int main()
{
string filename = "contacts.txt";
string tempfilename = "temp.txt";
ifstream ifs(filename);
ofstream ofs(tempfilename);
if (!ifs) {
cerr << "Error opening file " << filename << endl;
exit(EXIT_FAILURE);
}
if (!ofs) {
cerr << "Error creating temp file " << tempfilename << endl;
exit(EXIT_FAILURE);
}
string line;
bool delete_this_line = false; // 标记变量,表示当前行是否需要删除
while (getline(ifs, line)) {
// 如果需要删除该行,则将标记变量设为true
if (line.find("delete_this_line") != string::npos) {
delete_this_line = true;
continue;
}
// 如果当前行不需要删除,则将其写入临时文件
if (!delete_this_line) {
ofs << line << endl;
}
// 重置标记变量
delete_this_line = false;
}
ifs.close();
ofs.close();
// 删除原文件并更名临时文件
remove(filename.c_str());
rename(tempfilename.c_str(), filename.c_str());
return 0;
}