【问题标题】:How to swap lines in a text file?如何交换文本文件中的行?
【发布时间】:2017-03-26 13:52:51
【问题描述】:

我有一个文本文件;假设文本文件有 10 行。 我想在第 3 行和第 6 行之间交换。

我该怎么做?另外,我无法为交换创建任何临时文件。

【问题讨论】:

  • 为了安全起见,您需要一个临时文件...
  • 如果不能创建临时文件,为什么不将所有文件加载到行数组中呢?然后换入程序,重写文件。
  • 我编辑了我的问题
  • 我恢复了最新的编辑,因为它使现有答案无效。如果你想对答案添加限制,你最好问一个不同的问题。这将增加您获得好答案的机会。

标签: c++ text file-io swap


【解决方案1】:

为使此解决方案正常工作,行不能包含单个空格,因为它将用作分隔符。

const std::string file_name = "data.txt";

// read file into array
std::ifstream ifs{ file_name };
if (!ifs.is_open())
    return -1; // or some other error handling
std::vector<std::string> file;
std::copy(std::istream_iterator<std::string>(ifs), std::istream_iterator<std::string>(), std::back_inserter(file));
ifs.close();

// now you can swap
std::swap(file[2], file[5]);

// load new array into file
std::ofstream ofs{ file_name, std::ios_base::trunc };
if (!ofs.is_open())
    return -1; // or some other error handling
std::copy(file.begin(), file.end(), std::ostream_iterator<std::string>(ofs, "\n"));

【讨论】:

  • 虽然在 C++17 中我们可以使用这样的函数式风格很酷,但它不适合错误处理。使用函数式风格,我们不能让流抛出异常,也不能区分 openread 错误(都设置了故障位)。使用本地流变量可以更好地做到这一点。
  • @zett42 我不明白。由于第一个条件,该文件存在。我认为不可能有任何读取错误,因为每个字节都可以解释为一个字符。所以我不明白为什么使用本地流变量是一个优势,不能设置错误,为什么要使用它们?
  • 文件存在,由于第一个条件 ...你不能确定。首先它是一个race condition,这意味着在调用is_regular_file() 和构造ifstream 之间可能会发生一些事情,这会使第一次检查无效。此外,检查文件的类型与打开文件不同。您可以成功检查类型,但由于缺少权限而无法打开。
  • @zett42 你说得对,我现在明白了 :) 非常感谢,现在已修复。
【解决方案2】:

警告:这将覆盖您的原始文件!!!

#include <fstream>
#include <vector>
#include <string>

int main()
{
    ifstream in("in.txt");
    if (in.is_open())
    {
        std::vector<std::string> content;
        for (std::string line; std::getline(in, line); )
        {
            content.push_back(line);
        }
        in.close();
        std::iter_swap(content.begin() + 2, content.begin() + 5);

        ofstream out("in.txt");
        if (out.is_open()) {
            for (auto i : content)
            {
                out << i << std::endl;
            }
            out.close();
        }
    }
}

【讨论】:

  • 什么都没有是什么意思?不管你喜不喜欢,你总得讲点故事。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-14
  • 2013-05-27
  • 2011-01-02
  • 1970-01-01
  • 1970-01-01
  • 2014-02-07
相关资源
最近更新 更多