C++程序查找和替换文件中的字符串

标签 c++

这是一个初学者问题。我试图在文本文件中找到一个字符串并将其替换回同一个文件。以下代码可以很好地将文件内容收集到缓冲区中并替换字符串。但是当我试图将数据保存回同一个文件时,它充满了一些垃圾字符。请让我知道我做错了什么?

#include <iostream>
#include <fstream>
using namespace std;

const char *fileName = "Test.dat";

int main () {

// This is where we'll put the stuff we read from file
char buffer[ 100 ];


ifstream finout(fileName, ios_base::in | ios_base::out | ios_base::binary);

if(!finout.is_open())
{
    cout << "Can not open file " << endl;
    return(1);
}

while (finout.getline(buffer, sizeof(buffer))
{
    string g( buffer );
    string search = "am";
    string replace = "was";
    long j;

    if ( (j = g.find(str2)) != string::npos)
    {    
        g.replace(g.find(str2), str2.length(), "str");
        finout.write((char *) &g, sizeof(g)); //This won't work 

    }

cout << g << "\n";
finout.close();
return 0;
}

我的 Test.dat 文件包含以下信息:

Hello, How are you?
I am fine.

最佳答案

  • 当你作为一个文本文件读/写时,不要用ios_base::binary打开它
  • 你把 finout.close(); 放在你的阅读循环中,所以它只对一行有效。
  • 当您以文本形式读取/写入文件时,请使用文本流方法和运算符。

关于C++程序查找和替换文件中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15332581/

相关文章:

C++ <algorithm> 替换所有不工作的事件

c++ - SDL_event KEYDOWN行为问题

c++ - 名称不会出现在我程序的底部

c++ - 有效检查 C++ 中 float 组的值变化

c++ - 这里有循环依赖吗?

c++ - 重载订阅运算符()或[],不重复代码

c++ - 为什么 imwrite on BMP 图像卡住/不返回?

c++ - 使用邻接矩阵的深度优先算法无法正常工作

c++ - 为二叉搜索树复制构造函数编写辅助函数

c++ - 黑莓 10 中的 Web 服务