【问题标题】:c++ : ofstream issuesc++ : ofstream 问题
【发布时间】:2013-10-12 10:53:06
【问题描述】:

谁能告诉我这是怎么回事?

#include <stdio.h>
#include <fstream>
#include <iostream>
#include <sstream>
#include <vector>

class writeManager
{
    std::vector<double> valueVector;
    std::ofstream ofsFile;

public:

    writeManager(void);
    void writeOnFile(int);
    void openOfsStreams(void);
    void closeOfsStreams(void);

};

writeManager::writeManager(void)
{
    openOfsStreams();
    ofsFile << "FIRST LINE" << std::endl;
    closeOfsStreams();
}

void writeManager::writeOnFile(int input)
{
    openOfsStreams();

    if(ofsFile.good())
    {
        ofsFile << input << std::endl;
    }
    else
    {
        std::cout << "Hey!" << std::endl;
    }

    ofsFile.close();
}

void writeManager::openOfsStreams(void)
{
    ofsFile.open("/home/user/example.txt");
}

void writeManager::closeOfsStreams(void)
{
    ofsFile.close();
}

int main()
{
    writeManager writeObject;
    for (unsigned int i = 0; i!= 5; i++)
    {
        writeObject.writeOnFile(i);
    }
}

我想在文件“example.txt”上看到这个输出

FIRST LINE
0
1
2
3
4

但我只得到

4

PS:没有“嘿!”被打印出来了。

【问题讨论】:

    标签: c++ file ofstream


    【解决方案1】:

    问题是您多次打开和关闭文件,每次打开文件都会破坏以前存在的内容。

    您可能应该只在构造函数中打开文件一次(不要在那里关闭文件)。

    另一种方法是以“追加”模式打开文件,但这会非常低效,打开文件是一项昂贵的操作。正如 Liho 建议的那样

    ofsFile.open("/home/user/example.txt", std::ofstream::out | std::ofstream::app);
    

    【讨论】:

      【解决方案2】:

      当您多次打开ofstream 时,它总是从头开始重写。

      可能的解决方案之一是使用app 标志,即更改:

      ofsFile.open("/home/user/example.txt");
      

      ofsFile.open("/home/user/example.txt", std::ofstream::out | std::ofstream::app);
      

      更好的办法是在构造函数中打开这个ofstream 一次,然后在析构函数中关闭它。

      【讨论】:

      • 我相信std::ofstream::out 对于ofstream 来说是不必要的。
      • @MatthieuM.:但是,它不会有任何错误。它只是再次明确表示您正在打开一个用于输出的流。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多