Here is probably a very noob question for you: how (if at all possible) can I return ifstream from a function?
Basically, I need to get the database file name from the user, and if the database with this name does not exist, then I need to create this file for the user. I know how to do this, but only asking the user to restart the program after creating the file. I wanted to avoid this inconvenience for the user, if possible, but the function below does not compile in gcc:
ifstream getFile() { string fileName; cout << "Please enter in the name of the file you'd like to open: "; cin >> fileName; ifstream first(fileName.c_str()); if(first.fail()) { cout << "File " << fileName << " not found.\n"; first.close(); ofstream second(fileName.c_str()); cout << "File created.\n"; second.close(); ifstream third(fileName.c_str()); return third;
EDIT: sorry, forgot to tell you where and what happened to the compiler:
main.cpp:45: note: synthesized method 'std::basic_ifstream<char, std::char_traits<char> >::basic_ifstream(const std::basic_ifstream<char, std::char_traits<char> >&)' first required here
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 main () line:
main.cpp:27: note: synthesized method 'std::basic_ifstream<char, std::char_traits<char> >::basic_ifstream(const std::basic_ifstream<char, std::char_traits<char> >&)' first required here
c ++ fstream ifstream ofstream
wrongusername
source share