首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用fstream写入

使用fstream写入
EN

Stack Overflow用户
提问于 2013-06-19 01:20:09
回答 1查看 19.7K关注 0票数 4

我正在尝试在指定的文件中查找行,并将其替换为我的行。我不能访问将要运行这段代码的机器上的库,所以我创建了一个自定义文件。问题似乎在于对fstream对象的write调用。我想知道你们谁能帮上忙。另外,我的getline循环在到达文件末尾之前就停止了,我不确定为什么。

代码语言:javascript
复制
#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

代码语言:javascript
复制
Hi
Today is June 18
I like pizza
I like pepperoni

输出为:

代码语言:javascript
复制
Match
No runtime error: I like deep dish pizza
Hi
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-06-19 01:29:14

代码语言:javascript
复制
myStream.write(temp2.c_str(), 100);
myStream << temp2 << endl;

为什么要把这个写到文件中两次,为什么告诉它“我喜欢深盘披萨”是100个字符的长度?只需使用第二行就可以完成您想要的操作。

我认为循环结束的原因是你在读文件的时候写了它,这导致了getline的混乱。如果文件很小,我会将整个文件读入stringstream,替换您想要替换的行,然后将整个stringstream写出到一个文件中。就地更改文件要困难得多。

示例:

代码语言:javascript
复制
#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();
}

运行方式如下:

代码语言:javascript
复制
g++ example.cpp -o example
./example Hi.txt Hi 'I like deep dish pizza'
票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17175062

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档