如何交换文本文件中的行
How to swap lines in a text file?
我有一个文本文件;假设文本文件有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();
}
}
}
相关文章:
- 文本文件中的单词链表
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 如何将内容数组写入文本文件?
- 无法通过空白将文本文件行分隔为矢量
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- C++将文本文件中的数据读取到结构数组中
- 在指针的帮助下,文本文件中单词的频率
- 将字符指针十六进制转换为字符串并保存在文本文件C++中
- 将值从二维数组输出到文本文件
- 如何使用 c++ 实现并发文件/文本编辑?
- 我需要转换一些代码,以便它适用于输入和输出文件文本
- 通过套接字发送二进制文件.文本文件有效,其他文件无效
- 将大型数据文件拆分为多个小文件(文本格式)
- 如何读取输入文件(文本文件)并将输入验证为有效整数
- 从文本文件/文本流中读取Q字符串错误
- 从文本文件(文本解析器)C++中读取行和列的逻辑
- 如何将*.css文件(文本文件)的内容与附加信息存储在新文件中?
- 关于内存映射文件和使用大文件文本编辑器
- 如何在读取文件文本时跳过"n"
- 使用libzip从.zip获取文件(文本除外)