删除文本文件C ++的一部分 [英] Remove parts of text file C++

查看:79
本文介绍了删除文本文件C ++的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为copynumbers.txt的文本文件,在使用示例"时,我需要删除一个数字后的一些数字,这将是一个包含以下内容的文本文件

I have a text file called copynumbers.txt that I need to delete some numbers after a number while using Example would be a text file containing the following

   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15

每个整数应占用4个字节的空间.

each integer should occupy 4 byte spaces.

我想删除或删除数字7到15,同时保留1到6,然后再添加数字30.

I want to delete or get rid of number 7 to 15 while keeping 1 through 6 then adding the number 30 to it.

因此文件将保留1到6并摆脱7到15,然后我要在文件结尾处保留30.

so then the file would keep 1 to 6 and get rid of 7 to 15 then after that I want to at 30 at the end of it.

我的新文件应如下所示

1 2 3 4 5 6 30

1 2 3 4 5 6 30

我的问题是如何在不覆盖数字1到6的情况下做到这一点?因为当我使用

std::ofstream outfile;
outfile.open ("copynumbers.txt");

它将覆盖所有内容,并且在文件中仅保留30个

it will override everything and leave only 30 in the file

当我使用

ofstream outfile("copynumbers.txt", ios::app);

它将在15之后追加30,但不会删除任何内容.

It will just append 30 after 15 but does not delete anything.

我的一些代码:

#include <iostream>
#include <fstream>
using namespace std;
int main() {
    ofstream outfile("copynumbers.txt", ios::app);

    outfile.seekp(0, outfile.end);

    int position = outfile.tellp();

    cout << position;

    //outfile.seekp(position - 35);

    outfile.seekp(28);
    outfile.write("  30",4);

    outfile.close();    

    return 0;
}

推荐答案

尝试就地"修改文件通常是一个坏主意-如果出现任何问题,则最终会导致文件损坏或丢失.通常,您会执行以下操作:

It's generally a bad idea to try to modify a file "in place" - if anything goes wrong then you end up with a corrupted or lost file. Typically you would do something like this:

  • 打开原始文件以供输入
  • 创建用于输出的临时文件
  • 读取输入文件,进行处理,写入临时文件
  • 如果成功,则:
    • 删除原始文件
    • 将临时文件重命名为原始文件名

    这不仅是一种更安全的策略,还使修改内容的过程变得更加容易,例如要从文件中删除"某些内容,您只需在读取输入时跳过该部分即可(即不要将其写入输出文件中).

    As well as being a safer strategy, this makes the process of modifying the contents easier, e.g. to "delete" something from the file you just skip over that part when reading the input (i.e. just don't write that part to the output file).

    这篇关于删除文本文件C ++的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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