c++ - 用 fstream 在最后一行写

标签 c++ string file c++11 fstream

我试图替换文本文件中的字符串。类似于 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 行:

Hi My name is amir and also my friend's name is amir too!
Hi My name is amir and also my friend's name is amir too!
Hi My name is amir and also my friend's name is amir too!
Hi My name is amir and also my friend's name is amir too!

当我运行程序时,我得到了这个。

Hi My name is reza and also my friend's name is reza too!
Hi My name is reza and also my friend's name is reza too!
Hi My name is reza and also my friend's name is reza too!
Hi My name is amir and also my friend's name is amir too!

最后一行有什么问题?

我认为问题出在这里:

if (flagforwrite){ 
                    file.seekp(flag);
                    file << buffer << "\n";
                    if(file.bad()) cout << "Error\n";
            }

为什么旗帜总是指线?

我正在使用 GNU GCC 编译器。

最佳答案

我找到问题了!是eof()造成的! 所以我没有使用 while(!file.eof()) 我使用了 while(file.getline(buffer,100))

我也将 file.tellg() 移动到末尾,并定义了这样的行:streampos line=file.tellg();

关于c++ - 用 fstream 在最后一行写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35165320/

相关文章:

c++ - 如何使用 C++ 在 Windows 和 Linux 中清除控制台

c++ - 为什么我的 Qt 应用程序在执行时不显示 GUI?

java - 使用java中的Substring方法提取字符并进行匹配

javascript - 这些 javascript DNA 补体算法是否等效且最优?

asp.net - 为什么我的 ASP Page.Request.Files[] 总是空的?我已经尝试了所有发布的修复程序

java - 为什么我们需要在文件 channel 中使用文件锁,因为操作不是并发访问的?

c++ - 具有相同简单改编结构属性的 boost::spirit::qi 规则会产生编译错误

c++ - 在 BB10 中使用 OpenGL ES 的用户界面

javascript - 在javascript中将字符串转换为utf-8

c - 结构和文件处理