Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

WriteString problem

Status
Not open for further replies.

Fylom

Programmer
Apr 14, 2002
4
CA
Hi.

I'm trying to read a file, search for a particular string, and then replace it with something else. I can easily read and search, but the writting part do not work and I don't understand. As a new C++ programer, I need help !

Here's the code I was roughly using:


void ReadWrite()
{

CStdioFile vFile;
CString line;

vFile.Open ("Test.ini", CFile::modeCreate | CFile::modeNoTruncate | CFile::modeReadWrite);
while (vFile.ReadString (line))
{
if (line=="DesiredText") vFile.WriteString ("New text");
}
vFile.Close ();
}


Thanks
 
Without trying your code out and without a description of what exactly is going wrong with it, I suspect that you should drop the CFile::modeNoTruncate mode from the Open function. I also suspect you should be using the base class (CFile) seek functions to correctly position the file marker. I may be wrong but you could try it.
 
I don't think you can do that so easily... you need to have the file pointer setup correctly.

I have dealt with this issue before... in the end I determined an easier way was to read the entire file into a vector CStrings or something, do all the required formatting on the CStrings and then ouput a new vector to a new file.
 
Yes, you're probably right - I couldn't be certain without actually testing the code, I was working on theory only. Sucking the entire file into an array of CStrings sounds like a good way to go. I can't think of a more solid/efficient way to accomplish the problem.
 
I think that you can read a string from base file and then to put it in other file. If you need to change a string, then you can change it in this new file. When you get EOF string, then you must delete old file and rename new file with name of old one. If you are working with a big file then this is the right way to do it, but if your file is small then you can use CStringList because this is the faster way for you.
 
I finally succeed the task. I've used a temp file to back up what is next after the line I was going to change. I use seek to move back the pointer to the begining of the line I wanted to change. I also had to clear the end of the original file because if the new line is shorter than the new one, then the file was polluted with scrap...
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top