xtensa1408
xtensa1408

Reputation: 594

using ios::ate over-write data

My task is to write in a precise position into file.txt with C++ And because my file is static ( it will not be changed) I decided to count the position of curseur where I have to write. ( I know it isn't the best idea to di this) This is my file and I have to write after '=' : enter image description here

It is clear that I want to over-write "null;" But I don't understand why "int main" in the otehr line is also over-writed! Have a look to the following please to undersatnd my problem: enter image description here

My questions are the following:

The is my attempt :

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
   ofstream monFlux("client.txt",ios::in |  ios::ate);
   if(monFlux)    
{
    monFlux.seekp(61, ios::beg);
    int position = monFlux.tellp(); 

    monFlux<< "DECryptBlockWithPCRYPT(d);";


  }
    else
    {
        cout << "ERROR" << endl;
    }
   system("pause");
   return 0;
}

Upvotes: 1

Views: 718

Answers (1)

foraidt
foraidt

Reputation: 5709

First, it looks like you're opening an output stream for reading (ios::in) is that correct?

I don't think you can insert characters the way you describe.
Your approach is more like a human would do it in a text editor. The stream object on the other side just gives you access to the bytes on the disk. It has no "select and replace" text function.

I think this approach could work:

  1. Open an input stream for reading the file and an output stream for writing one.
  2. Stream the first N characters directly to the output stream.
  3. Skip the "null" and insert your replacement string.
  4. Stream the rest of the input file into the output stream.
  5. On success, replace the original file with the new one.

Upvotes: 2

Related Questions