【问题标题】:fstream write/read to a binary file doesn't work as expected.!fstream 对二进制文件的写入/读取无法按预期工作。!
【发布时间】:2013-09-19 22:49:01
【问题描述】:
#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();
   }

使用这段代码,我只想将一个名为“my”的字符串插入到“helloworld”字符串的 2 字节位置。但它没有插入它(即使我正在寻找正确的位置)。谁能帮帮我?

【问题讨论】:

  • 我想我知道,但是对于稍后阅读这篇文章的其他人,你能描述一下输出是什么吗?
  • 在同一个文件上打开两个流对我来说看起来很可疑。

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


【解决方案1】:

来自ios::mode的文档

ios::app:

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

删除ios::app,您将能够在`"helloworld" 中将"my" 写在"ll" 上。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    相关资源
    最近更新 更多