You can use this replaceAll function on every line , and have your "replace in file function" built upon it.
I modified it to return a boolean if a replacement occurred :
bool replaceAll(std::string& str, const std::string& from, const std::string& to) {
if(from.empty())
return false;
size_t start_pos = 0;
bool res = false;
while((start_pos = str.find(from, start_pos)) != std::string::npos) {
str.replace(start_pos, from.length(), to);
start_pos += to.length(); // In case 'to' contains 'from', like replacing 'x' with 'yx'
res = true;
}
return res;
}
Then, what is left to you is :
- Iterate over all the lines of the input file
- Find and replace every occurrence of your string on the file
- If a replacement occurred, write the line count
- Write the replaced string on another file
The ReplaceInFile
method :
void replaceInFile(const std::string& srcFile, const std::string& destFile,
const std::string& search, const std::string& replace)
{
std::ofstream resultFile(destFile);
std::ifstream file(srcFile);
std::string line;
std::size_t lineCount = 0;
// You might want to chech that the files are properly opened
while(getline(file,line))
{
++lineCount;
if(replaceAll(line, search, replace))
std::cout << "Match at line " << lineCount << " " << replace << std::endl;
resultFile << line << std::endl;
}
}
Example:
int main()
{
replaceInFile("sourceFile.txt", "replaced.txt", "match", "replace");
return 0;
}