Hi,
I am trying to edit a text file through c++ and this is what I tried but don't know why its not working
here's my class
1 2 3 4 5 6 7
class A{
public:
int a;
char b[15];
char c[15];
};
A q;
the test.txt file
1 2 3 4
1 one number1
2 two number2
3 three number3
4 four number4
and the code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
fstream fio;
fio.open("text.txt",ios::in|ios::ate);
fio.seekg(0);//putting pointer to 0
long pos;
while(!fio.eof())//untill the file ends
{
pos=fio.tellg();//tell the position of stuff
fio>>q.a>>q.b>>q.c;//taking values
if(q.a==3)//if the value is 3
{
fio.seekg(pos);//put the cursor to that element
fout<<10<<' '<<"new name"<<' '<<"new type"<<'\n';
}
}
1) If you are going to only read to file, use ifstream.
2) There is no need for ate flag
3) Consider opening file in stream constructor.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
std::ifstream fin("test.txt");
int count;
while( fin >> a[i].b >> a[i].c >> a[i].d)
++count;
fin.close(); //We want to close file explicitely, because we need to manipulate it later
for(int i = 0; i < count; ++i)
if(a[i].b == 2)
//...
std::ofstream fout("temp.txt");
for(int i = 0; i < count; ++i)
fout << a[i].b<<' '<<a[i].c<<' '<<a[i].d<<'\n';
fout.close(); //Ditto
std::remove("test.txt"); //delete test file
std::rename("temp.txt","test.txt"); //rename the temp to text
won't ios::out (default) delete the all old records?
If you do not specify out flag, it will not be used at all. fstream do not have implicit "always on" flag like istream (ios::in) and ostream (ios::out) do, it just have a default ios::in | ios::out value, which will be replaced completely by any user-defined one. And std::ifstream do not even have out as default.