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.

Recommended Answers

All 6 Replies

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.

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.

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

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().

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();

Thanks NathanOliver, we haven't read about vectors yet.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.