【发布时间】:2016-05-11 22:59:00
【问题描述】:
我试图替换文本文件中的字符串。类似 replace() 函数。
代码如下:
#include <iostream>
#include <fstream>
#include <cstring>
Using namespace std;
int main()
{
fstream file("C:\\Users\\amir hossein\\Desktop\\Temp1\\test1.txt");
char *sub; sub = new char[20]; sub = "amir";
char *replace1; replace1 = new char[20]; replace1 = "reza";
char *buffer; buffer = new char[100];
int i, temp; streampos flag;
int c=0,mark;
bool flagforwrite=0;
if (file.is_open()){
while (!file.eof()) {
flag = file.tellg();
file.getline(buffer, 100); //We'll Search Sub inside of Buffer, if true, we'll replace it with Replace string
flagforwrite=0;
for (i=0;buffer[i];i++){
mark=i; c=0;
while (sub[c] && sub[c]== buffer[mark]){
c++; mark++;
}
if (!sub[c]){ //Make Changes in The Line
for (int j=i,count=0;count<strlen(replace1);j++,count++) buffer[j] = replace1[count]; //until here, we've replace1d the sub
flagforwrite=1;
}
}
if (flagforwrite){ //Write The line ( After Whole Changes In line have been made!!
file.seekp(flag);
file << buffer << "\n"; // ENDL here IS SUPER IMPORTANT!! IF you don't put it, I'll mess it up
if(file.bad()) cout << "Error\n";
}
}
}
else cout << "Error!!\n";
file.close();
delete[] sub;
delete[] replace1;
delete[] buffer;
return 0;
}
我想用“reza”替换“amir”。
我的文本文件包含 4 行:
嗨,我的名字是 amir,我朋友的名字也是 amir!
嗨,我的名字是阿米尔,我朋友的名字也是阿米尔!
嗨,我的名字是阿米尔,我朋友的名字也是阿米尔!
嗨,我的名字是 amir,我朋友的名字也是 amir!
当我运行程序时,我得到了这个。
嗨,我的名字是 reza,我朋友的名字也是 reza!
嗨,我的名字是 reza,我朋友的名字也是 reza!
嗨,我的名字是 reza,我朋友的名字也是 reza!
嗨,我的名字是 amir,我朋友的名字也是 amir!
最后一行有什么问题?
我认为问题就在这里:
if (flagforwrite){
file.seekp(flag);
file << buffer << "\n";
if(file.bad()) cout << "Error\n";
}
为什么flag总是指行?
我正在使用 GNU GCC 编译器。
【问题讨论】:
-
` while (!file.eof()) {`
-
file.seekp(flag);您以文本模式打开了文件。使用诸如seekp之类的函数不会给你想要的结果。 stackoverflow.com/questions/33926595/text-file-binary-search如果你想成功处理文件,请以二进制模式打开文件(ios::binary)。 -
永远不要这样做:
while (!file.eof()):stackoverflow.com/questions/5605125/… 它经常会弄乱最后一行。 -
请编写 C++ 代码,而不是使用 C++ 的 C 代码。您正在泄漏内存,您甚至不应该首先分配内存,而是使用 std::string,它支持在此处手动实现的所有字符串操作。
标签: c++ string file c++11 fstream