【问题标题】:Replacing the data in a specific row in the txt file替换txt文件中特定行的数据
【发布时间】:2021-08-26 13:34:58
【问题描述】:

我正在构建一个 TCP 服务器应用程序。两种不同类型的请求来自客户端。在第一种请求类型中,客户端从某一行开始请求一定数量的行信息。比如客户端抛出一个请求,比如我想从第 5 行开始读 3 行。到目前为止还可以,我已经完成了这部分,但是现在让我们来看看我有困难的部分。在第二种类型的请求中, 客户端想从某行开始更改某行中的字符。例如从第6行开始更改4行.txt文件由1s和0s组成.txt文件如下。

1
0
1
0
1

当收到两行换行请求时,txt文件应该如下,从第四行开始。

1
0
1
1
0

我不使用索引号来标识行号,而是首先使用循环读取整个文件,并在每次迭代时将读取的数据推送到向量中。因此,当我想读取特定行时,我调用该向量的所需索引。 我们感兴趣的代码部分如下所示。

std::fstream myfile("fc3-4.txt", std::ios_base::in);
        int reg;
        std::vector<int> registers_vec;
        while (myfile >> reg)
        {
            registers_vec.push_back(reg);
        }

由于我的研究,我发现要删除特定数据,但这对我不起作用,因为例如,如果我将要删除的值写入 1,它会删除 txt 文件中的所有 1。如上所述,如何从某一行开始替换一定数量的行。在此先感谢

【问题讨论】:

  • 你并没有准确地展示什么不起作用,但是你可以通过调用registers_vec.erase(register_vec.begin() + index)来删除向量的单个数据。
  • @Lala5th 是的,正如你所说,我可以从vector中删除我想要的元素,但我真正想要的是从txt文件中删除我想要的元素并用一个新的替换它.
  • @Lala5th 我将向量用于只读。但是现在我需要更改txt文件中的数据。我对用于阅读的矢量所做的更改不再重要。

标签: c++ file


【解决方案1】:

首先将完整的文件读入内存。然后关闭文件。

在内存中进行修改。

然后,修改完成后,将完整的向量写入文件。

例如:

#include <iostream>
#include <fstream>
#include <vector>
#include <iterator>

int main() {
    // Open the file and check, if it could be opened
    if (std::ifstream dataStream{ "fc3-4.txt" }; dataStream) {

        // Read all vallues in vector data
        std::vector data(std::istream_iterator<int>(dataStream), {});
        // And close the file
        dataStream.close();


        // Do any modification. Example flip bits for line 6 to 8
        for (size_t line{ 6 }; data.size() > 8 and line < 8; ++line)
            data[line] = 1 - data[line];


        // Write all file to file
        {
            if (std::ofstream dataStream{ "fc3-4.txt" }; dataStream) {

                // Write all data to file
                std::copy(data.begin(), data.end(), std::ostream_iterator<int>(dataStream, "\n"));
            }
            else std::cerr << "\nError, Cannot open file for writing\n";
        }
    }
    else std::cerr << "\nError, Cannot open file for reading\n";
}

【讨论】:

    猜你喜欢
    • 2017-08-15
    • 1970-01-01
    • 2017-11-02
    • 1970-01-01
    • 2014-04-23
    • 2016-08-21
    • 2016-09-04
    • 2011-02-01
    相关资源
    最近更新 更多