fstream写/读到二进制文件不能按预期工作。

时间:2013-09-19 22:49:02

标签: c++ file-io ifstream fileinputstream ofstream

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

使用这段代码我只想在'helloworld'字符串的2byte位置插入一个名为'my'的字符串。但它没有插入它(即使我正在寻找正确的位置)。任何人都可以帮我吗?

1 个答案:

答案 0 :(得分:0)

来自ios::mode

的文档
  

IOS ::应用程式:

     

内容到文件的当前内容。这个标志只能是   在流中打开用于仅输出操作。所有输出操作都在   文件末尾,附加

删除ios::app,您就可以在“helloworld”中的"my"上写"ll"

请注意,您将无法在文件中“插入”某些内容 - 实现此目的的唯一方法是从原始文件中读取并将新数据写入新文件[或者读取您想要的内容修改,插入所需的文本,并在修改位后写回所需的部分。