Search code examples
c++functionvariablesglobalofstream

std::ofstream variable definition problems


I am having problems with my ofstream variable outfile. I define it globally, and then try to change it within a function:

ofstream outfile("C:\\folder1\\folder2\\file1.file");

void a() {
    ofstream outfile("C:\\folder3\\folder4\\file2.file");
}

main(){
    a();
    outfile << "TEST";
}

This does not work. If I try to remove the ofstream in the second declaration, I get errors.

NOTE: My debugger broke


Solution

  • This does not work. If I try to remove the ofstream in the second declaration, I get errors.

    Sure, there's no such operator() overload for ofstream, supposed you've been writing

    void a() {
        outfile("C:\\folder3\\folder4\\file2.file");
    }
    

    Note that there's also no assignment operator defined, such writing

    void a() {
        outfile = ofstream("C:\\folder3\\folder4\\file2.file");
    }
    

    can't be used either.

    The closest you can get is

    void a() {
        outfile.close();
        outfile.open("C:\\folder3\\folder4\\file2.file");
    }
    

    The real question is IMHO, why you need to declare outfile in the global scope. Usually it's not necessary at all.