C ++ Fstream替换特定行? [英] C++ Fstream to replace specific line?

查看:541
本文介绍了C ++ Fstream替换特定行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我很难说如何做到这一点。我设法到达我想替换的行,但我不知道如何替换它。

okay i'm stumped on how to do this. I managed to get to the line I want to replace but i don't know how to replace it.

说一个名为file.txt的文件包含这个:

say a file called file.txt containts this:

1
2
3
4
5

,我想替换第3行,所以它说4而不是3.我该怎么做?

and I want to replace line 3 so that it says 4 instead of 3. How can I do this?

#include <Windows.h>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

fstream file;
string line;

int main(){
file.open("file.txt");
for(int i=0;i<2;i++){
getline(file,line);
}
getline(file,line);
//how can i replace?
}


推荐答案

在读/写模式下,您可以通过查找(包括寻找当前位置)在读取和写入之间切换。但是,请注意,写入的字符覆盖现有字符,即不插入新字符。例如,这可能看起来像这样:

Assuming you have opened a file in read/write mode you can switch between reading and writing by seeking, including seeking to the current position. Note, however, that written characters overwrite the existing characters, i.e., the don't insert new characters. For example, this could look like this:

std::string line;
while (std::getline(file, line) && line != end) {
}
file. seekp(-std::ios::off_type(line.size()) - 1, std::ios_base::cur);
file << 'x';

即使你在正确的位置寻找需要将流处于未绑定状态。尝试在阅读和写作之间切换,而不寻求导致未定义的行为。

Even if you are at the right location seeking is needed to put the stream into an unbound state. Trying to switch between reading and writing without seeking causes undefined behavior.

这篇关于C ++ Fstream替换特定行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆