c++程序查找和替换文件中的字符串
C++ program to find and replace a string in file
这是一个初学者的问题。我试图在文本文件中找到一个字符串,并将其替换回相同的文件。下面的代码可以很好地将文件的内容收集到缓冲区中并替换字符串。但是,当我试图保持数据回到同一个文件,它是充满了一些垃圾字符。请让我知道我做错了什么?
#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();
放在你的读取循环中,所以它只工作一行。 - 当你以文本形式读写文件时,使用文本流方法和操作符。
您正在尝试使用sizeof()
操作符读取字符串的大小。
这不起作用,因为它是一个关键字,它给了你对象或类型的非动态大小。
您应该使用g.size()
来访问字符串的大小!
但是首先,你可以处理流来处理你的bug:
finout << g;
就可以了。
首先,你想读和写一个文件,所以使用fstream而不是ifstream。其次,您有一个文本文件,所以不要使用ios_base::binary第三(char*) &g其中g是std::string不起作用,使用g.c_str()代替。(只写finout & lt; & lt;g;
现在你可以开始考虑实现了…
相关文章:
- 将字符指针十六进制转换为字符串并保存在文本文件C++中
- 有没有办法从非C/C++文件中读取C++原始字符串文字的内容
- 如何打开并写入一个名称取自C++中字符串的文件
- 如何从二进制文件中读取字符串
- 如何在 c++ 中使用 getline 从文件中读取字符串?
- 将字符串与文件上的数据进行比较
- 用户输入字符串的文件附加问题..C++
- 如何从文件中读取两个字符串和数字数组,并将它们存储在对象向量中
- 如何使字符串出现在编译的二进制可执行文件的开头?
- 使用文件内容作为硬编码字符串
- 将文件复制到自定义位置,存在字符串转换问题
- 将二进制字符串/文件内容从 c++ 传递到节点 js
- 在字符串.h文件中调用函数而不带对象
- 将带有引号和逗号的字符串文件读入字符串数组
- 如何从字符串/文件中分离字符和整数
- 将字符串文件存储到动态数组中
- 如何用C++将字符串文件Txt解析成数组
- 如何用Boost::Spirit解析复杂的字符串文件
- 如何从C语言的第二行读取字符串文件
- 一个很好的性能替代PHP-字符串/文件操作