Question

#include <iostream>
#include <string.h>
#include <fstream>
#include <conio.h>
using namespace std;
int main(int argc, char*argv[])
  {
ifstream fpr;
ofstream fpw;

char * rec1 = "helloWorld";
char * rec2 = "my";
char out1[50];
char out2[50];
fpw.open("sample.txt",ios::in|ios::binary|ios::app);
if(fpw.fail())
{
    cout<<"The file could not be opened!\n";
    exit(1); // 0 – normal exit, non zero – some error
}
fpr.open("sample.txt",ios::out|ios::binary);
if(fpr.fail())
{
    cout<<"The file could not be opened!\n";
    exit(1); // 0 – normal exit, non zero – some error
}
fpw.write(rec1,10);
fpr.read(out1,10);
out1[10] = '\0';
cout<<out1<<"\n";
fpw.seekp(2,ios::beg);
fpw.write(rec2,2);
fpr.seekg(0,ios::beg);
fpr.read(out2,strlen(rec1));

cout<<"\n"<<out2<<"\n";
getch();
   }

With this code I just want to insert a string named 'my' to the 2byte location of 'helloworld' string. But it doesn't insert it(even though I'm seeking to the correct location). Could anyone help me out?

Was it helpful?

Solution

from documentation on ios::mode

ios::app:

the content to the current content of the file. This flag can only be used in streams open for output-only operations.All output operations are performed at the end of the file, appending

Remove the ios::app, and you will be able to write "my" over "ll" in `"helloworld".

Note that you won't be able to "insert" something into a file - the only way to achieve that is to read from the original file and write the new data to a new file [or read whatever is after you want to modify, insert the text you want, and write back the parts you want after the modified bit].

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top