0

Suppose my file a.txt has "ABC" written in it. Now I want to write a small b before capital B in the file. How will I do it?

I've tried to do it but i'm having problems.
1. When opened in app mode seekp doesn't work.
2. When opened normally previous written data is erased.

4
Contributors
6
Replies
30
Views
3 Years
Discussion Span
Last Post by MRehanQadri
0

If I was doing this I would read each line of the file into a string array. After that I would go through each string in the array and insert a b in front of every B. Then I would just overwrite the contents of the file with the modified array.

Edited by NathanOliver

0

Open your file(a.txt) and a temp file. Read the a.txt file writing the results to the temp file. If one of the characters to be written is B then write b first.

Finally, delete a.txt and rename temp to a.txt.

0

HOw will you overwrite the file with modified string? Same problem will occur which I've mentioned.

0

Unfortunately, there is no real answer other than to read the file contents after the point of insertion, and re-write them with an offset equal to the size of the text you are inserting (one byte, in this case). Given the size of the file, it may be easier to simply read the whole text beyond the insertion point into memory, do the insertion, and write it all back.

Can you tell us something of the actual goal of your program? This question has the feel of a simplified example. For more elaborate editing, you might want to read up about the 'buffer gap' technique, which is described in detail in the online textbook The Craft of Text Editing.

As for why seekp() "isn't working", in append mode, just how were you trying to use it? Keep in mind that seekp() sets the position for writing, but to set the position for reading, you need to use seekg().

Edited by Schol-R-LEA

0

This is a shell for what I would do.

std::string filename;
// get the filename and put it in the string

std::ifstream fin(filename.c_str());
std::vector<std::string> file;
std::string line;

// read in file
while (std::getline(fin, line))
    file.push_back(line)

fin.close();
for(int i = 0; i < file.size(); i++)
{
    // code to go through the string and add 'b' before 'B' here
    // using the string methods find() and insert() will help here
}

// write the vector to the file replacing the old version of the file
std::ofstream fout(filename.c_str())
for (int i = 0; i < file.size(); i++)
    fout << file[i];

fout.close();

Edited by NathanOliver

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.