使用 fstream 写入文件

4

我正在尝试查找指定文件中的一行并用我的行替换它。由于我无法访问将在这些机器上运行的库,因此我创建了一个自定义文件。问题似乎出现在对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;
}

Hi.txt

Hi
Today is June 18
I like pizza
I like pepperoni

输出结果如下:
Match
No runtime error: I like deep dish pizza
Hi
1个回答

7
myStream.write(temp2.c_str(), 100);
myStream << temp2 << endl;

为什么你要两次将这段话写入文件,并且告诉它"I like deep dish pizza"有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'

我写了两次,因为第二行似乎不起作用。我将尝试stringstream方法,看看效果如何。 - Babbu Maan
1
@BabbuMaan 如果有用的话,我已经包含了一个如何做到这一点的示例。 - Brendan Long

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接