Hi,
Stuck on using replace. I can use find to locate a string, and it indicates
the correct position, but replace doesn't overwrite or add any text to the file.
I have algorithm.h included, fstream.h, etc. Checked file permissions etc. Not sure what I'm doing wrong.
Well duh.
You're changing an std::string whose contents were COPIED from the file. The std::string is in no way connected to the file.
I'd read the entire file into a string, perform the replace, then write back.
You might also want to get rid of that ios::app there, since that puts the read and write pointers at the end of the file, meaning attempts to read should fail.
You are also relying on some implicit casting and range-of-datatype limitations.
string::find() returns a size_type which is almost surely unsigned, which means in theory the return value will ALWAYS be >= 0. However, you are stuffing the return code into a (signed) int. Since string::npos is typically (unsigned)-1 found just happens to be -1 when it is not found.
IMHO you should not be relying on this behavior, particularly since the solution is very simple, ie,
1 2 3 4
string::size_type found = line.find( mystring );
if( found != line.npos ) {
// ....
}
Thank You for comments. I tried again placing read file contents in a string (buf), then using find/replace.
I'm still having the same problem which is not being able to write to the random access file. The replacestring shows up in std out (console) but not in the file. I can open a new fstream and write the buf contents to that file, but not the same file. Also confused about sentinel value for 'while' when writing to avoid endless loop. My solution is ugly. Would appreciate more comments if you have them.
I keep answering my own thread. I worked with this a bit more. Still not sure what the correct or most elegant solution is for reading/writing to a random access file using find/replace. But did see that reading the file into a string (buf), closing the file, then opening the stream again for write and writing the contents of the string to the file seemed to work. Not sure why reading and writing on the same open stream was not working.
In C++, using file streams are bit tricky for rewriting a file. More tricky for rewriting in a file with single open (with ios::in | ios::out).
I would try with read() and write() methods than getline() or getch() for rewrite a file.
Check for the reference on this same site for reading and write the files with read() and write() methods of fstream. To seek a file position in the stream, you could use seekg() or tellg() etc methods too.
This is how things are done: you read an entire relevant block of data (in this case, the whole file) to memory, you perform the necessary operations, then you write back. And you don't read character by character unless you enjoy wasting system resources. Instead, use read operations that write to an array.