Note that there are some explanatory texts on larger screens.

plurals
  1. POReturning ifstream in a function
    text
    copied!<p>Here's probably a very noobish question for you: How (if at all possible) can I return an ifstream from a function?</p> <p>Basically, I need to obtain the filename of a database from the user, and if the database with that filename does not exist, then I need to create that file for the user. I know how to do that, but only by asking the user to restart the program after creating the file. I wanted to avoid that inconvenience for the user if possible, but the function below does not compile in gcc:</p> <pre><code>ifstream getFile() { string fileName; cout &lt;&lt; "Please enter in the name of the file you'd like to open: "; cin &gt;&gt; fileName; ifstream first(fileName.c_str()); if(first.fail()) { cout &lt;&lt; "File " &lt;&lt; fileName &lt;&lt; " not found.\n"; first.close(); ofstream second(fileName.c_str()); cout &lt;&lt; "File created.\n"; second.close(); ifstream third(fileName.c_str()); return third; //compiler error here } else return first; } </code></pre> <p>EDIT: sorry, forgot to tell you where and what the compiler error was:</p> <pre><code>main.cpp:45: note: synthesized method ‘std::basic_ifstream&lt;char, std::char_traits&lt;char&gt; &gt;::basic_ifstream(const std::basic_ifstream&lt;char, std::char_traits&lt;char&gt; &gt;&amp;)’ first required here </code></pre> <p>EDIT: I changed the function to return a pointer instead as Remus suggested, and changed the line in main() to "ifstream database = *getFile()"; now I get this error again, but this time in the line in main():</p> <pre><code>main.cpp:27: note: synthesized method ‘std::basic_ifstream&lt;char, std::char_traits&lt;char&gt; &gt;::basic_ifstream(const std::basic_ifstream&lt;char, std::char_traits&lt;char&gt; &gt;&amp;)’ first required here </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload