sparker256
sparker256

Reputation: 21

Trying to return std::ifstream from a function

When I try to use this function I get a error at the two returns. If I comment them out I do not get the errors. Is there any reason why this should not work?

 std::ifstream bipgetConfigurationPath() {
    char bipacfFilename[256], bipacfFullPath[512];
    char *bipconfigPath;
    char *bipdefaultConfigFile;
    const char *bipdefaultConfigFileName;
    bipdefaultConfigFile = "./Resources/plugins/Xsaitekpanels/D2B_config.txt";
    bipdefaultConfigFileName = "D2B_config.txt";
    XPLMGetNthAircraftModel(0, bipacfFilename, bipacfFullPath);
    bipconfigPath = strstr(bipacfFullPath, bipacfFilename);
    strncpy(bipconfigPath, bipdefaultConfigFileName, sizeof(bipacfFilename));
    puts(bipacfFullPath);

    // Check if ACF-specific configuration exists
    std::ifstream bipcustomStream(bipacfFullPath);
    if (bipcustomStream.good()) {
        return bipcustomStream;
    } else {
        std::ifstream bipdefaultStream(bipdefaultConfigFile);
        if (bipdefaultStream.good()) {
            return bipdefaultStream;
        }

    }
}

Thanks Bill

Upvotes: 0

Views: 2777

Answers (3)

AJG85
AJG85

Reputation: 16197

As others have said file streams are not copyable. Maybe something more like this:

bool bipgetConfigurationPath(std::ifstream& ifs) {

    std::string bipdefaultConfigFileName("D2B_config.txt");

    // ...

    ifs.open(bipdefaultConfigFileName);
    return ifs.good();
}

Upvotes: 2

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361482

All the stream classes in C++ are made noncopyable by having made their copy-constructor private. That means, you cannot return stream objects by value. Read this for detail. End of the story.

So the solution is to pass a stream object to the function as reference, and open the file in the function, and return from it, or create the stream object using new and return the pointer to the stream object from the function, but then if you do so, you've to delete the object when you're done with it. I personally would not do either of them.

I will probably encapsulate the stream and the behaviour/work you would like to do with the object, in a class.

In C++11, you can use std::move to move the stream object, as streams are movable.

Upvotes: 6

Anon Mail
Anon Mail

Reputation: 4770

std::streams are not copyable.

Upvotes: 6

Related Questions