C++代码以查找和修改/替换 .c 文件中的字符串
C++ code to find and modify/replace a string in .c file
我的任务是在.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';
}
相关文章:
- 将字符指针十六进制转换为字符串并保存在文本文件C++中
- 有没有办法从非C/C++文件中读取C++原始字符串文字的内容
- 如何打开并写入一个名称取自C++中字符串的文件
- 如何从二进制文件中读取字符串
- 如何在 c++ 中使用 getline 从文件中读取字符串?
- 将字符串与文件上的数据进行比较
- 用户输入字符串的文件附加问题..C++
- 如何从文件中读取两个字符串和数字数组,并将它们存储在对象向量中
- 如何使字符串出现在编译的二进制可执行文件的开头?
- 使用文件内容作为硬编码字符串
- 将文件复制到自定义位置,存在字符串转换问题
- 在 c++ 中连接字符串和整数,以便在 C++ 11 不支持计算机的情况下读取多个文件
- 声明要在 qml 和 cpp 文件中使用的全局字符串
- C 通过char读取文件字符串的文件char;崩溃
- 我不明白如何将 toupper 和 isalpha 与.txt文件字符串输入一起使用
- 在 CPP 文件中使用 make 文件字符串变量
- 编译 PyGAMMA Mac Lion:g++ 找不到标准的 C++ 头文件(字符串/iostream..)
- 如何在c++中使用文件字符串作为命令
- 使用 TinyXML 解析 XML 文件字符串
- 递归下降解析器帮助(不读取文本文件字符串)