Returning ifstream in a function

后端 未结 4 2141
日久生厌
日久生厌 2021-02-13 11:13

Here\'s probably a very noobish question for you: How (if at all possible) can I return an ifstream from a function?

Basically, I need to obtain the filename of a databa

4条回答
  •  旧巷少年郎
    2021-02-13 11:44

    bool checkFileExistence(const string& filename)
    {
        ifstream f(filename.c_str());
        return f.is_open();
    }
    
    string getFileName()
    {
        string filename;
        cout << "Please enter in the name of the file you'd like to open: ";
        cin >> filename;
        return filename;
    }
    
    void getFile(string filename, /*out*/ ifstream& file)
    {
        const bool file_exists = checkFileExistence(filename);
        if (!file_exists) {
            cout << "File " << filename << " not found." << endl;
            filename = getFileName();  // poor style to reset input parameter though
            ofstream dummy(filename.c_str();
            if (!dummy.is_open()) {
                cerr << "Could not create file." << endl;
                return;
            }
            cout << "File created." << endl;
        }
        file.open(filename.c_str());
    }
    
    int main()
    {
        // ...
        ifstream file;
        getFile("filename.ext", file);
        if (file.is_open()) {
            // do any stuff with file
        }
        // ...
    }

提交回复
热议问题