Using fstream Record

I am trying to find a line in the specified file and replace it with my line. I do not have access to the library on machines. I run this, so I created a custom file. The problem seems to be related to the write invocation for the fstream object. I was wondering if any of you would help. Also, my getline loop stops until it reaches the end of the file, and I'm not sure why.

#include <iostream> #include <fstream> #include <string> #define TARGET2 "Hi" using namespace std; void changeFile(string fileName){ fstream myStream; myStream.open(fileName.c_str(),fstream::in | fstream::out); string temp; string temp2 = "I like deep dish pizza"; while(getline(myStream, temp)){ if(temp == TARGET2){ cout << "Match" << endl; myStream.write(temp2.c_str(), 100); myStream << temp2 << endl; cout << "No runtime error: " << temp2 << endl; } cout << temp << endl; } myStream.close(); } int main (void){ changeFile("Hi.txt"); return 0; } 

Hi.txt

 Hi Today is June 18 I like pizza I like pepperoni 

Output:

 Match No runtime error: I like deep dish pizza Hi 
+2
c ++ fstream
source share
1 answer
 myStream.write(temp2.c_str(), 100); myStream << temp2 << endl; 

Why do you write this to a file twice, and why do you tell him that β€œI love pizza with a big dish” is 100 characters long? Just using the second line, you have to do what you want.

I think the reason the loop ends is because you write the file as you read it, which causes getline confusion. If the file is small, I would just read it all in stringstream , replacing the string you want to replace, and then write the entire stringstream file to the file. Changing a file in place is much more complicated.

Example:

 #include <fstream> #include <iostream> #include <sstream> int main(int argc, char** argv) { /* Accept filename, target and replacement string from arguments for a more useful example. */ if (argc != 4) { std::cout << argv[0] << " [file] [target string] [replacement string]\n" << " Replaces [target string] with [replacement string] in [file]" << std::endl; return 1; } /* Give these arguments more meaningful names. */ const char* filename = argv[1]; std::string target(argv[2]); std::string replacement(argv[3]); /* Read the whole file into a stringstream. */ std::stringstream buffer; std::fstream file(filename, std::fstream::in); for (std::string line; getline(file, line); ) { /* Do the replacement while we read the file. */ if (line == target) { buffer << replacement; } else { buffer << line; } buffer << std::endl; } file.close(); /* Write the whole stringstream back to the file */ file.open(filename, std::fstream::out); file << buffer.str(); file.close(); } 

Run as:

 g++ example.cpp -o example ./example Hi.txt Hi 'I like deep dish pizza' 
+5
source share

All Articles