写入现有二进制文件的中间 c++

编程入门 行业动态 更新时间:2024-10-18 03:34:47
本文介绍了写入现有二进制文件的中间 c++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我正在尝试打开一个二进制文件进行写入而不删除内容.但我不想写eof.我想写入文件中的特定位置.

I'm trying to open a binary file for writing without erasing the content. But I do not want to write to eof. I want to write to a specific position in file.

这是一个小例子:

ofstream out("test.txt", ios::binary | ios::app);
for(int i = 0; i < 100; i++)
    out.put('_');
out.write("Hallo", 5);
out.close();

ofstream out2("test.txt", ios::binary | ios::app);
out2.seekp(10);
out2.write("Welt", 4);
out2.close();

如果使用应用程序,则搜索不起作用.如果不使用应用程序打开文件会删除数据.有人知道答案吗?

If using app, seek doesn't work. If not using app opening file erases data. Does anybody know an answer?

推荐答案

尝试seekp的第二个重载,它允许你提供一个偏移量和一个方向,这个在您的情况下可能是文件的开头(即 ios_base::beg).这当然假设您知道自己在做什么,并且您想做的只是覆盖现有数量的字符.

try the second overload of seekp, which allows you to provide an offset and a direction, this could be begining of file in your case (i.e. ios_base::beg). This of course assumes you know what you are doing and all you want to do is overwrite an existing number of characters.

这里是完整的工作示例:

here is fully working example:

#include <iostream>
#include <fstream>

using namespace std;
int main()
{
  {
    ofstream out("test.txt", ios::binary);
    for(int i = 0; i < 100; i++)
      out.put('_');
    out.write("Hallo", 5);
  }

  {   
    fstream out2("test.txt", ios::binary | ios::out | ios::in);
    out2.seekp(10, ios::beg);
    out2.write("Welt", 4);
  }
}

这篇关于写入现有二进制文件的中间 c++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-17 20:36:15,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/921486.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:二进制文件

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!