Arlington
Arlington

Reputation: 79

C++ deleting or overwriting existing information in a file

Is there a way in C++ using standard libraries to overwrite binary data in a large file and preserve the rest of the existing data in the file without loading the entire file first?

Example: if I have a file "MyFile" containing the text "ABC" and want to replace 'A' with 'Q', is there a way to do so without loading "BC" into memory?

What I have so far:

#include <fstream>

int main(int argc, char** argv)
{
    std::fstream f;
    f.open("MyFile",std::ios::in);
    while (f.good())
    {
        char Current = f.get();
        if (Current == 'A')
            break;
    }
    int Location = f.gcount()-1;
    f.close();

    if (Location < 0)
    {
        printf("Nothing to do.\n");
        return EXIT_SUCCESS;
    }
    else
    {
        f.open("MyFile",std::ios::in | std::ios::out);
        f.seekp(Location);
        f.write("Q",1);
        //f.put('Q');
        //f << "Q";
        f.close();
        return EXIT_SUCCESS;
    }
}

That seems to work now - thanks all.

Upvotes: 1

Views: 345

Answers (1)

nvoigt
nvoigt

Reputation: 77285

Open your file as std::ios::in | std::ios::out, then when you have your position of your 'A', move your "input caret" back to that position using f.seekg(Location); and write to the file.

Please keep in mind, you can only replace/overwrite. You cannot append to the middle of a file.

This should work:

#include <fstream>
#include <iostream>

int main()
{
    std::fstream f("d:\\file.txt", std::ios::in | std::ios::out);

    char c;

    while (f >> c)
    {
        if (c == 'A')
        {
            f.seekp(-1, std::ios_base::cur);
            f.put('Q');
            return EXIT_SUCCESS;
        }
    }

    std::cout << "Nothing to do." << std::endl;

    return EXIT_SUCCESS;
}

Upvotes: 1

Related Questions