首页 > 解决方案 > 数组中的ofstream一直写入同一个文件

问题描述

我有一个如下所示的结构:std::list -> 包括 VolataliteAnalyzer 类型的对象列表 *(这是我的自定义类) -> VolataliteAnalyzer 对象保留一个 ofstream 对象,如下面的代码所示。我正在调用以下方法来编写适当的文件

void VolataliteAnalyzer::writeToFile (unsigned long orderBookId,double volatalite,double currentWarrantPrice,double stockPrice,double expireDate,double strikePrice)
{

    logger.logMessage(new MessageInfoLog(std::string(__PRETTY_FUNCTION__)+" Writing File For :"+std::to_string(orderBookId)));
    if (!warrantFile.is_open()) {
        std::string filePath = std::string(FILE_NAME)+std::string("_")+std::to_string(orderBookId)+std::string(FILE_EXT);
        warrantFile.open (filePath,std::ios_base::app);
        logger.logMessage(new MessageInfoLog(std::string(__PRETTY_FUNCTION__)+" Creating File:"+filePath));

    }

    warrantFile << this->getCurrentDate()+DELIMETER+std::to_string(volatalite)+DELIMETER+std::to_string(currentWarrantPrice)+DELIMETER+std::to_string(stockPrice)+DELIMETER+std::to_string(expireDate)+DELIMETER+std::to_string(strikePrice)+"\n";

} 

但是,当我调用此方法时,对于数组中的不同对象,它总是写入同一个文件。但相反,它应该为数组中的每个对象写入唯一文件。我已经测试了很多次,但无法理解原因。我怀疑如果 ofstream 对象是单例或类似的东西?

class VolataliteAnalyzer {

public:

    double selectedVolatalite=0;

    VolataliteAnalyzer();
    void writeToFile(unsigned long orderBookId,double volatalite,double currentWarrantPrice,double stockPrice,double expireDate,double strikePrice);
    void finishWriting();
    bool loadFromFile(unsigned long orderBookId);
    void getSelectedVolatalite(int dayCount);

private:
        Logger& logger;
        std::ofstream warrantFile;
        std::ifstream warrantReader;
        std::string getCurrentDate();
        std::list<Volatalite *> dailyVolatalites;

        Volatalite* getVolatalite(std::string date);
};

标签: c++data-structures

解决方案


推荐阅读