如何使用C++编辑文本文件中的行
How to edit a row in a text file with C++?
我有一个这样的txt文件:
"shoes":12
"pants":33
"jacket":26
"glasses":16
"t-shirt":182
我需要更换夹克的数量(例如从 26 到 42)。所以,我写了这段代码,但我不知道如何编辑有"夹克"一词的特定行:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ifstream f("file.txt");
string s;
if(!f) {
cout< <"file does not exist!";
return -1;
}
while(f.good())
{
getline(f, s);
// if there is the "jacket" in this row, then replace 26 with 42.
}
f.close();
return 0;
}
为了修改文本文件中的数据,您通常需要读取将整个文件放入内存中,在那里进行修改,然后重写它。 在这种情况下,我建议为条目定义一个结构,对于name
和quantity
条目,平等定义为名称,以及要读写的超载operator>>
和operator<<
它来自文件。 然后,您的整体逻辑将使用以下函数:
void
readData( std::string const& filename, std::vector<Entry>& dest )
{
std::ifstream in( filename.c_str() );
if ( !in.is_open() ) {
// Error handling...
}
dest.insert( dest.end(),
std::istream_iterator<Entry>( in ),
std::istream_iterator<Entry>() );
}
void
writeData( std::string const& filename, std::vector<Entry> const& data )
{
std::ifstream out( (filename + ".bak").c_str() );
if ( !out.is_open() ) {
// Error handling...
}
std::copy( data.begin(), data.end(), std::ostream_iterator<Entry>( out ) );
out.close();
if (! out ) {
// Error handling...
}
unlink( filename.c_str() );
rename( (filename + ".bak").c_str(), filename.c_str() );
}
(我建议在错误处理中引发异常,这样你就不会不得不担心if
的 else 分支。 除了创建ifstream
首先,错误条件异常。
首先,这不可能以幼稚的方式。假设您要编辑所述行但写入更大的数字,则文件中不会有任何空格。所以通常中间的eidts是通过重写文件或写入副本来完成的。程序可能会使用内存、临时文件等,并对用户隐藏这些信息,但是在文件中间追逐一些字节只能在非常混乱的环境中工作。
所以你要做的是写另一个文件。
...
string line;
string repl = "jacket";
int newNumber = 42;
getline(f, line)
if (line.find(repl) != string::npos)
{
osstringstream os;
os << repl << ':' << newNumber;
line = os.str();
}
// write line to the new file. For exmaple by using an fstream.
...
如果文件必须相同,则可以将所有行读取到内存(如果有足够的内存),或者使用临时文件进行输入或输出。
相关文章:
- 文本文件中的单词链表
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 如何将内容数组写入文本文件?
- 无法通过空白将文本文件行分隔为矢量
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- C++将文本文件中的数据读取到结构数组中
- 在指针的帮助下,文本文件中单词的频率
- 将字符指针十六进制转换为字符串并保存在文本文件C++中
- 将值从二维数组输出到文本文件
- 如何使用 c++ 实现并发文件/文本编辑?
- 我需要转换一些代码,以便它适用于输入和输出文件文本
- 通过套接字发送二进制文件.文本文件有效,其他文件无效
- 将大型数据文件拆分为多个小文件(文本格式)
- 如何读取输入文件(文本文件)并将输入验证为有效整数
- 从文本文件/文本流中读取Q字符串错误
- 从文本文件(文本解析器)C++中读取行和列的逻辑
- 如何将*.css文件(文本文件)的内容与附加信息存储在新文件中?
- 关于内存映射文件和使用大文件文本编辑器
- 如何在读取文件文本时跳过"n"
- 使用libzip从.zip获取文件(文本除外)