使用 fstream 写入
Using fstream write
>我正在尝试在指定的文件中查找一行并将其替换为我的行。 我无权访问我将在其上运行它的计算机上的库,因此我创建了一个自定义文件。 问题似乎是对 fstream 对象的写入调用。 我想知道你们中是否有人可以提供帮助。 另外,我的 getline 循环在到达文件末尾之前停止,我不确定为什么。
#include <iostream>
#include <fstream>
#include <string>
#define TARGET2 "Hi"
using namespace std;
void changeFile(string fileName){
fstream myStream;
myStream.open(fileName.c_str(),fstream::in | fstream::out);
string temp;
string temp2 = "I like deep dish pizza";
while(getline(myStream, temp)){
if(temp == TARGET2){
cout << "Match" << endl;
myStream.write(temp2.c_str(), 100);
myStream << temp2 << endl;
cout << "No runtime error: " << temp2 << endl;
}
cout << temp << endl;
}
myStream.close();
}
int main (void){
changeFile("Hi.txt");
return 0;
}
嗨.txt
Hi
Today is June 18
I like pizza
I like pepperoni
输出为:
Match
No runtime error: I like deep dish pizza
Hi
myStream.write(temp2.c_str(), 100);
myStream << temp2 << endl;
你为什么要把这个写到文件中两次,为什么你告诉它"我喜欢深盘披萨"是 100 个字符长?仅使用第二行应该可以执行所需的操作。
我认为循环结束的原因是您在阅读文件时正在写入文件,这会导致getline
感到困惑。如果文件很小,我会将整个内容读入一个stringstream
,替换要替换的行,然后将整个stringstream
写到文件中。就地更改文件要困难得多。
例:
#include <fstream>
#include <iostream>
#include <sstream>
int main(int argc, char** argv) {
/* Accept filename, target and replacement string from arguments for a more
useful example. */
if (argc != 4) {
std::cout << argv[0] << " [file] [target string] [replacement string]n"
<< " Replaces [target string] with [replacement string] in [file]" << std::endl;
return 1;
}
/* Give these arguments more meaningful names. */
const char* filename = argv[1];
std::string target(argv[2]);
std::string replacement(argv[3]);
/* Read the whole file into a stringstream. */
std::stringstream buffer;
std::fstream file(filename, std::fstream::in);
for (std::string line; getline(file, line); ) {
/* Do the replacement while we read the file. */
if (line == target) {
buffer << replacement;
} else {
buffer << line;
}
buffer << std::endl;
}
file.close();
/* Write the whole stringstream back to the file */
file.open(filename, std::fstream::out);
file << buffer.str();
file.close();
}
像这样运行:
g++ example.cpp -o example
./example Hi.txt Hi 'I like deep dish pizza'
相关文章:
- 使 std::fstream 写入文件末尾,但从头开始读取
- 如何使用单个fstream创建、读取和写入文件
- 在链表上写入和读取 fstream 的函数
- std::fstream 需要很长时间才能将大数据写入.csv文件中
- 将二进制数据写入C 中的Fstream
- 如何在 c++ 中同时使用 'fstream' 写入和读取文件
- C++ fstream 未正确写入对象
- 尝试使用 fstream 将字符写入文件:'operator<<'不匹配
- 使用 fstream 读取文件后,我无法立即写入文件
- 如果在类 temlpate 中使用,fstream 是否会在编译时通过读取和写入来访问 hardrive?
- 从 fstream 中读取后,为什么它似乎需要在写入之前清除它的好位
- 为什么与cstdio和std::fstream相比,SDL_RWops在写入文件时表现如此糟糕
- 使用fstream写入gz
- 写入文件 与 FStream 不起作用
- 读取,操纵和写入C 文档,主要使用FSTREAM和数组
- C Fstream未显示写入的contenst
- 在 C++ 中使用 Fstream 创建和读取/写入文件
- 在C++中打开并写入现有的fstream,而不进行覆盖/清除
- fstream没有在文件中写入任何内容
- 无法写入 fstream 文件