-
Data File Help!!!
I want to update a data file. If a == target then I want it to ignore a b and c and then print the rest of the file to the same file.
Here is my code
Code:
void list(string target)
{
string a, b, c;
ifstream tar("data.txt");
ofstream fout("data.txt");
while(! tar.eof())
{
tar >> a >> b >> c;
if(a != target)
{
fout << a << b << c << endl;
}
}
}
I have tried writing to data2.txt instead of data.txt and it works OK. But when I have it like the above my data.txt file looks like this 6.01347e - 154 with nothing else.
Thanks in advance
-
I think you may have to close some streams or something before writing to them. Search for examples of fstream
-
You shouldn't read and write to the file at the same time. Normally you would read in the file, storing the data that you want to keep in some sort of container. A string would be fine here (using +=). Then you write it all back out.
Another thing to remember is that your loop will run one two many times. You should not check for eof() as the while loop control. Instead you should check the return value of the call to operator>>.
-
Another thing to remember is that calling ofstream on a file with no openmode (2nd) argument will automatically truncate it. This is unfortunate if it's like, important.