如何在不完全覆盖所有内容的情况下写入文件 [英] How to write a file with without entierly overwriting everything

查看:68
本文介绍了如何在不完全覆盖所有内容的情况下写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作自己的地图编辑器,并使用fstream编写需要编写的文件.
我写文件时遇到的问题是我希望程序更改文件中的数字(每次程序打开文件时都会被写入),但是当程序写文件时,它会覆盖所有更改的意图或添加.
例如,我希望程序像这样更改文件:
(文件中的现有内容):
00 00 00 01

如果正在写一些东西,我希望它像这样添加它:
> 01< 00 00 00 01

但是我的程序现在正在做的事情是覆盖这样的所有内容:
(文件中的现有内容):
00 00 00 01

(正在将内容写入文件):
> 01<< br mode ="hold"/>
因此,基本上,我想知道如何添加内容而不是将其覆盖.

I''m making my own map editor and i''m using fstream to write the file that needs writing.
The problem I have with writing the file is that I want the program to change the numbers inside the file (each time the program opens the file is beeing written to), but when the program is writing to the file it overwrites everything insted of changing or adding.
For example I want the program to change the file like this:
(the existing content in the file):
00 00 00 01

and if something is being written I want it to add it like this:
>01< 00 00 00 01

but what my program is doing right now is overwriting everything like this:
(the existing content in the file):
00 00 00 01

(things are being written to the file):
>01<<br mode="hold" />
So basically I want to know how to add stuff and not overwrite it.

推荐答案

您需要附加到文件中.您可能做错了什么.您可以显示文件编写代码吗?

使用fstream,您很可能需要使用ios::app附加到现有文件.
You need to append to the file. You are probably doing something wrong. Can you show your file writing code?

With fstream, you most likely need to use ios::app to append to the existing file.


假设您正在使用文本文件-将此文件转为
00 00 00 01
进入
> 01< 00 00 00 01

首先,您需要移动文件的现有内容,以便为额外的5个字符> 01<"腾出空间.

您需要从头开始,首先将最后一个字符移动所需的距离,然后再将其移动到末尾,依此类推,直到所有现有文本都已移动以为要插入的字符放下位置-现在原则.通常,您将使用缓冲区并一次移动块以加快处理速度.

除非您的文件很大,否则这样做不值得.对于小于5 MB的文件,只需使用合适的结构将所有内容加载到内存中,即可处理数据并再次将其写出.

如果您需要详细的解析,请查看 antlr [ ^ ]

问候
Espen Harlinn
Assuming you are using a text file - to turn this
00 00 00 01
into
>01< 00 00 00 01

You first need to move the existing content of the file to make room for the additional 5 characters ">01< ".

You need to start at the end, first moving the last character the required distance, then the next to last, and so on until all the existing text has been moved to make place for the characters you want to insert - now that''s the principle. Usually you would use a buffer and move blocks at a time to speed things up.

This isn''t worth the effort unless your file is quite big. For files less than - let''s say 5 MB - just load everything into memory using a suitable structure, manipulate your data and write it out again.

If you need elaborate parsing take a look at antlr[^]

Regards
Espen Harlinn


这篇关于如何在不完全覆盖所有内容的情况下写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆