简体   繁体   中英

fstream write/read to a binary file doesn't work as expected.!

#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?

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].

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM