0
fstream& fileReading(const string& signalFile, const string& backgroundFile){
    ofstream fileName;
    fileName.open(signalFile, ios::in | ios::binary);

 //does more stuff here

    return fileName;
}

I receive the following error message:

non-const lvalue reference to type 'fstream' cannot bind to a value of unrelated type 'ofstream'.

I am not sure what it means or why I am receiving it.

I have a feeling it has to do with the declaration of the fstream and the ofstream.

When i change the return type to ofstream, I receive a message which states: Reference to stack memory associated with local Variable 'fileName' returned.

I would like a little help understanding what all of this means and how I can refactor the function/method to return a file i would create and write to.

Any help would be greatly appreciated. beginner in c++ having to learn the language on the fly.

Channing
  • 166
  • 1
  • 9
  • 1
    `fstream` supports reading and writing. Returning something that supports only writing doesn't make much sense. Anyway, see http://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope, the difference being a reference instead of a pointer. – chris Apr 15 '15 at 05:44
  • I still get the same issue with the stack memory once it is all 'fstream' @chris – Channing Apr 15 '15 at 05:47
  • 1
    @ForrestChanningHunter You can't return a reference to a local variable because the variable doesn't exist after the function returns. See [here](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) for details. – molbdnilo Apr 15 '15 at 05:59

2 Answers2

2

You have two issues here:

  • you are attempting to return a reference to a local object; the object gets destroyed at the end of the scope, then you would return a reference to it; this is invalid. Consider returning an instance, instead of a reference.

  • you are attempting to return a different object than the function should return. Consider changing the function to return an ofstream instance, then make sure it is returned through moving:

    std::ofstream fileReading(const string& signalFile,
                               const string& backgroundFile)
    {
        return std::ofstream{ signalFile, ios::in|ios::binary };
    }
    
utnapistim
  • 26,809
  • 3
  • 46
  • 82
0

you must return address of file handler (&fileName) instead of fileName so your code must be:

fstream& fileReading(const string& signalFile, const string& backgroundFile){
    ofstream fileName;
    fileName.open(signalFile, ios::in | ios::binary); 
    return fileName;
}

and you must call this funtion as follow:

fstream* fileHandlerPointer = fileReading("sample.txt" , "sample2.tct");
Mohsen Bahaloo
  • 257
  • 2
  • 2
  • 1
    The first code sample is *identical* to what the OP already posted, and comments have mentioned is already wrong. Paste the wrong code? – WhozCraig Apr 15 '15 at 07:03