如何交换文本文件中的行

How to swap lines in a text file?

本文关键字:文件 文本 何交换 交换      更新时间:2023-10-16

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

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

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

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"));

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

#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();
        }
    }
}