【发布时间】:2015-08-29 21:12:30
【问题描述】:
考虑我有以下文件(“testt.txt”)
abc
123
def
456
ghi
789
jkl
114
现在,如果我想更新名称 ghi 旁边的数字(即 789),
我该怎么做?
下面的代码无疑可以帮助我快速到达那里,但是如何快速更新呢?
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{
int counter = 0;
string my_string;
int change = 000;
ifstream file ( "testt.txt" );
while(!file.eof())
{
counter = counter + 1;
getline(file, my_string, '\n');
if (my_string == "ghi")
{
ofstream ofile ( "testt.txt" );
for (int i = 0; i < counter + 1; i++)
{
//reached line required i.e. 789
//how to process here?
}
ofile.close();
break;
}
}
cout << counter << endl;
file.close();
return 0;
}
显然这里的计数器是5对应“ghi”,
所以 counter + 1 将指向值789。怎么改成000?
------------已解决-----------最终代码-----
#include<iostream>
#include<fstream>
#include<string>
#include <cstdio>
using namespace std;
int main()
{
string x;
ifstream file ( "testt.txt" );
ofstream ofile ( "test2.txt" );
while (!file.eof())
{
getline(file,x);
if (x == "789")
{
ofile << "000" << endl;
}
else
ofile << x << endl;
}
file.close();
ofile.close();
remove("testt.txt");
return 0;
}
输出(“test2.txt”)
abc
123
def
456
ghi
000
jkl
114
【问题讨论】:
-
考虑使用数据库,因为使用简单的文件访问这些操作往往很复杂。无论如何,您处理问题的方式归结为“读取数据”,“修改数据”,“写入数据”,这很麻烦但可能。您究竟在哪一步遇到了问题?
-
你可以看到,它是用for循环写的,还有什么不用数据库也能用的方法??我的意思是将更新的数据写入新文件并删除旧文件..
-
@bikrathor 如果您拥有所有某些固定的数据位置,这是可能的。查看
std::basic_ostream::seekp()方法。
标签: c++ file iostream file-handling