|
#1
|
|||
|
|||
|
Problem with std::fstream
Hello,
I have :- #include<string> #include<iostream> #include<fstream> using namespace std; int main () { string line; std::fstream myfile("test.txt", std::ios::in | std::ios::out | std::ios::app); while (! myfile.eof() ) { getline (myfile,line); if (line == "IG") { myfile << "*****Here*****\n"; } } myfile.close(); return 0; } As you can see if I find in my file the string "IG", then I wish to append to that line *****Here***** The problem is, that all the contents up to that point are added to the file causing certain parts to be duplicated. Can someone please help ? Many thanks. |
|
#2
|
|||
|
|||
|
Oh.. You can't do that!
you cannot just up and write in the middle of a file stream this way. You are asking *someone* to let you write into the middle of bytes saved on the hard disk, IE to automatically shuffle the rest of the file down to make room for the new content. No low level tool is that smart, you will have to write this yourself. Something like: int main () { string line; std::fstream myfile("test.txt", std::ios::in | std::ios::out | std::ios::app); ofstream nt; nt.open("new.txt"); while (! myfile.eof() ) { getline (myfile,line); if (line == "IG") { nt << "******HERE****** "<< line <<endl; } else nt<<line<<endl; } myfile.close(); nt.close(); return 0; } and at the end, you can copy new over test in code (tell the os to copy it, etc), if you like, and delete new, etc to clean up automatically if that is your desire. Last edited by jonnin; 10-26-2009 at 04:54 PM. |
![]() |
| Bookmarks |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
Similar Threads
|
||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| Memory problem with Borland C3.1 | AZ1699 | C++ | 11 | 11-16-2007 01:23 PM |
| App Problem with MS Office ... | Shannon | VB Classic | 7 | 06-24-2007 09:47 PM |
| Re: Thank you; weird problem with OleDb provider objects. Anyone have this problem? | DK | .NET | 0 | 12-13-2001 01:06 PM |
| Arabic problem view | Ayman | VB Classic | 0 | 04-03-2000 02:08 AM |
| Problem with CryptoAPI and JCE | Jason Bock | VB Classic | 0 | 03-21-2000 07:48 PM |