Search code examples
c++fstream

c++ - Replacing one character at beginning of line in output stream with another one


What I need to do is read some parameters values from an input file in which comments are identified by putting * at the beginning of the line. The values in the "useful" lines are separated by semicolons like this:

10; 32541615; 0.18; 0.45; 0.00015; 0.01485; 0.03;

and I have multiple lines like this in my input file.

What I would like to do is insert a * at the beginning of each line once I've read it in such a way that if I read the file a second time I will skip that line and go directly to the following one.

I need this because my objective is to have multiple instances of my program running at the same time and accessing the file in sequence in order to get the input parameters they need. So I want that each instance will get different parameters.

What I thought to do is inserting a dummy character at the beginning of each line, like this:

b10; 32541615; 0.18; 0.45; 0.00015; 0.01485; 0.03;

and then replace it (b in this example) with * when I read it so that the second time I read the line it would be treated as a comment.

I tried to use put('*') and << '*' once I read b with a peek() call but the * character is always appended at the end of the file. I've read that although I can't write in the middle of a file I can overwrite in the middle of a file. What can I do?

Here is an example of a possible input file:

* FORMAT:
* MAX_HEIGHT; SEED; p0; p1; pd; pp; epsilon;

b10; 32541615; 0.18; 0.45; 0.00015; 0.01485; 0.03;
b40; 32541615; 0.18; 0; 0.00015; 0.01485; 0.03;

Solution

  • So you want to modify the file that you're reading? Then you basically have to rewrite it, from scratch.

    One common way to do it is by reading the whole file into memory, modify the in-memory buffer, then overwrite the file with the (modified) in-memory buffer.

    Another common way, if the file is to big to fit in memory, is to read line by line, modify the line, and write it to a new temporary file. Then when all of the input has been read you rename the temporary file as the actual file, thereby replacing the data in it.

    Both of these solutions can be used without you needing any special marker-character like the b at the beginning of the line to be replaced.