替换文件 C++ 中的行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4499095/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
replace line in a file C++
提问by Prasanth Madhavan
I'm trying to find a way to replace a line, containing a string, in a file with a new line.
我试图找到一种方法来用新行替换文件中包含字符串的行。
If the string is not present in the file, then append it to the file.
如果文件中不存在该字符串,则将其附加到文件中。
Can someone give a sample code?
有人可以提供示例代码吗?
EDIT : is there anyway if the line that i need to replace is at the end of the file?
编辑:无论如何,如果我需要替换的行在文件末尾?
采纳答案by karlphillip
Although I recognize that this is not the smartest way to do it, the following code reads demo.txtline by line and searches for the word cactusto replace it for orangeswhile writing the output to a secondary file named result.txt.
虽然我意识到这不是最聪明的方法,但以下代码逐行读取demo.txt并搜索单词cactus以将其替换为oranges,同时将输出写入名为result.txt的辅助文件。
Don't worry, I saved some work for you. Read the comment:
别担心,我为你保存了一些工作。阅读评论:
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
string search_string = "cactus";
string replace_string = "oranges";
string inbuf;
fstream input_file("demo.txt", ios::in);
ofstream output_file("result.txt");
while (!input_file.eof())
{
getline(input_file, inbuf);
int spot = inbuf.find(search_string);
if(spot >= 0)
{
string tmpstring = inbuf.substr(0,spot);
tmpstring += replace_string;
tmpstring += inbuf.substr(spot+search_string.length(), inbuf.length());
inbuf = tmpstring;
}
output_file << inbuf << endl;
}
//TODO: delete demo.txt and rename result.txt to demo.txt
// to achieve the REPLACE effect.
}
回答by ur.
To replace the last two lines in your file:
要替换文件中的最后两行:
- Use
fopen()
to open the file - Get the current file position with
fgetpos()
- Store always the last two file position and read line by line
- When you've reached the end of the file: The lower position is where you have to position to with
fseek()
- Now you can
fprintf()
your new lines to the file and close it withfclose()
afterwards.
- 使用
fopen()
打开文件 - 获取当前文件位置
fgetpos()
- 始终存储最后两个文件位置并逐行读取
- 当您到达文件末尾时:较低的位置是您必须定位的位置
fseek()
- 现在您可以
fprintf()
将新行添加到文件中,然后关闭它fclose()
。
回答by Philm
As mentioned, the code by KarlPhilip is a good starting point (thanks), but did not work correctly according to the ">= 0". Comparing to "0" it is known for MS CString-types and in C#, etc, but it seems not to work properly with the STL. E.g. in VS 2010 (only release), the C++ code behaved wrong with this compare without throwing an error!
如前所述,KarlPhilip 的代码是一个很好的起点(谢谢),但根据 ">= 0" 无法正常工作。与“0”相比,它在 MS CString 类型和 C# 等中是已知的,但它似乎不能与 STL 正常工作。例如,在 VS 2010(仅发行版)中,C++ 代码在此比较中表现错误,而不会引发错误!
Here is a correction to C++ standards: If some wizards have improvements, please post them. I think, it is a very useful and important question/snippet.
这是对 C++ 标准的更正:如果某些向导有改进,请发布它们。我认为,这是一个非常有用且重要的问题/片段。
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
string search_string = "cactus";
string replace_string = "oranges";
string inbuf;
// Todo: Check, if input_file exists before.
// Todo: Try/catch or check, if you have write access to the output file.
fstream input_file("demo.txt", ios::in);
ofstream output_file("result.txt");
while (!input_file.eof())
{
getline(input_file, inbuf);
size_t foundpos = inbuf.find(search_string);
if(foundpos != std::string::npos)
{
string tmpstring = inbuf.substr(0,spot);
tmpstring += replace_string;
tmpstring += inbuf.substr(spot+search_string.length(), inbuf.length());
inbuf = tmpstring;
}
output_file << inbuf << endl;
}
//TODO: delete demo.txt and rename result.txt to demo.txt
// to achieve the REPLACE effect.
}
I used the following replacement part inside the "if" from another SO question (The code above only replace the first occurrence):
我在另一个 SO 问题的“if”中使用了以下替换部分(上面的代码只替换了第一次出现):
if(foundpos != std::string::npos)
replaceAll(inbuf, search_string, replace_string);
//http://stackoverflow.com/questions/3418231/c-replace-part-of-a-string-with-another-string
//
void replaceAll(std::string& str, const std::string& from, const std::string& to)
{
size_t start_pos = 0;
while((start_pos = str.find(from, start_pos)) != std::string::npos)
{
size_t end_pos = start_pos + from.length();
str.replace(start_pos, end_pos, to);
start_pos += to.length(); // In case 'to' contains 'from', like replacing 'x' with 'yx'
}
}
回答by Roddy
If you want to change the length of (or delete) a line in the middle of a file, you will have to re-write all the subsequent lines.
如果要更改(或删除)文件中间一行的长度,则必须重新编写所有后续行。
There's no way of simply deleting or inserting characters into an existing file.
无法简单地将字符删除或插入到现有文件中。