C++代码以查找和修改/替换 .c 文件中的字符串

C++ code to find and modify/replace a string in .c file

本文关键字:文件 字符串 替换 代码 查找 修改 C++      更新时间:2023-10-16

我的任务是在.c文件中搜索一个字符串并使用c ++代码对其进行修改。我已经完成,直到搜索字符串,但修改它会给出错误。如果我将c文件的内容复制到文本文件并尝试修改它,它会给出相同的错误。所以我确定我的代码有问题。请帮助我是初学者。提前谢谢。我的代码:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string s1, s2;
  ifstream test("test.csv");
  while (test.eof()==0)      //test.eof() returns 0 if the file end is not reached
  {
    getline(test, s1, ',');     //reads an entire line(row) till ',' to s1
    getline(test, s2, 'n');
    cout << s1 + "= " +s2 << endl;
    fstream fileInput;
    int offset;
    string line;
    string search=s1;
    fileInput.open("IO_CAN_0_User.c");
if(fileInput.is_open()) {
    while(!fileInput.eof()) {
        getline(fileInput, line);
        if ((offset = line.find(search, 0)) != string::npos) {
            cout << "found: " << search << endl;
            string str;
            str=search;
            str.replace(str.begin()+25,str.begin()+31,"=s2  //");
            break;
        }
    }
    //cout << "string not found" << endl;
    fileInput.close();
}
else cout << "Unable to open file.";

if(test.eof()!=0)
    cout<<"end of file reached"<<endl;
    getchar();
    return 0;
  }
}

您面临的错误尚不清楚,但我可以看到一个大问题,即您的运行replace在空字符串上。

您的代码:

string str;
search=str;
str.replace(str.begin()+25,str.begin()+31,"=s2  //");

您创建str(默认情况下初始化为空字符串),将其分配给search(因此此字符串为空),然后调用replace尝试从 char 25 更改为 31,由于str为空,因此不存在。

更新
可能您需要修复替换,但是您不能期望文件更改:您正在修改的字符串在内存中,而不是文件的一部分。

因此,我会更改代码(尽可能多地使用您的代码):
* 添加输出文件
* 修复更换
*将输入文件的每一行(如果需要替换)保存在输出上

fileInput.open("IO_CAN_0_User.c");
ofstream  fileOutput;
fileOutput.open("output.c");
if(fileInput.is_open() && fileOutput.is_open() ) {
  while(!fileInput.eof()) {
    getline(fileInput, line);
    if ((offset = line.find(search, 0)) != string::npos) {
        cout << "found: " << search << endl;
        line.replace( offset, offset+search.size(), s2 );
    }
    fileOutput << line << 'n';
}