Question

can anyone tell me what's wrong with this?

#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);
    }
}

I'd like to see this output on file "example.txt"

FIRST LINE
0
1
2
3
4

but I get only

4

PS: no "Hey!" is printed.

Was it helpful?

Solution

The problem is that you open and close the file multiple times and each time you open the file you destroy the contents that were there previously.

Probably you should open the file once only in the constructor (and don't close the file there).

An alternative would be to open the file in 'append' mode, but that would be very inefficient, opening a file is an expensive operation. As Liho suggested

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

OTHER TIPS

When you open your ofstream multiple times, it always rewrites it from the beginning.

One of the possible solutions would be to use app flag, i.e. change:

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

to

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

Yet even better would be to open this ofstream just once in constructor and close it in destructor.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top