Parsing through every line of a file

Hey guys,
I'm trying to write a program that detects certain things in a file and replaces them. To do this I have created a function to iterate through the file line by line. Also, I have a function that replaces the text with whatever is necessary. However, it doesn't seem to work. Can someone please tell me what's wrong with my program and how to fix it?

1
2
3
4
5
6
7
8
9
std::ifstream file("file.txt");
	std::string line;
	while (std::getline(file, line))
	{
		myreplace(line, "[0]", "X");
		myreplace(line, "[1]", "Y");
		myreplace(line, "[2]", "Z");
		
	}


The code for the method myreplace is:
1
2
3
4
5
6
7
std::string myreplace(std::string &s,
	const std::string &toReplace,
	const std::string &replaceWith)
{
	return(s.replace(s.find(toReplace), toReplace.length(), replaceWith));
}

However, it doesn't seem to work.

Why doesn't it seem to work?

Do you realize that when dealing with a file you can only replace characters, you can't remove or add characters to the middle of a file?

closed account (E0p9LyTq)
There are some basic approaches you could take to achieve what you want:

1. Read the entire contents of the file into memory, manipulate the data in memory and when done write the altered contents back out to the file overwriting the old contents.

2. Read a chunk of data (usually a line if it is a text file), manipulate that data and write out to a temporary file. Repeat until the entire file is read/changed. Delete the old file and rename the temp file to the old name.

3. Do #1 but use a temp file as done in #2.
Topic archived. No new replies allowed.