Search code examples
c++fileifstream

ifstream does not open a file in the next iteration


I have two similar methods that open a file identically, but process them and return values a bit differently, yet while the first method does that successfully, the second method, which is called after the first one, fails.

I have tried changing the path to this file, its extension, but I think I miss some important knowledge about ifstream.

vector<User> Database::createUserDatabase()
{   
    vector<User> users;

    ifstream inputFile;
    inputFile.open(pathToFile, ios::in);

    //Some file processing

    inputFile.close();
    return users;
}

And that works perfectly, while

vector<User> Database::createBookDatabase()
{   
    vector<Book> books;

    ifstream inputFile;
    inputFile.open(pathToFile, ios::in);

    //Some file processing

    inputFile.close();
    return books;
}

fails to end whenever I check if the file has been opened or not using

inputFile.is_open()

These functions are defined in class files Database.cpp, User.cpp, Book.cpp, which are correctly linked to the main.cpp with the following content:

#include <iostream>
#include <cstdlib>
#include <string>
#include <cstring>
#include <sstream>
#include <vector>
#include <fstream>

#include "../lib/Book.h"
#include "../lib/User.h"
#include "../lib/Database.h"

using namespace std;

int main() 
{
    Database userDatabase("../database/users.txt", "users");
    Database bookDatabase("../database/lmsdb.txt", "books");

    vector<User> users = userDatabase.createUserDatabase();
    vector<Book> books = bookDatabase.createBookDatabase();

    return 0;
}

Here are my Project directories

Using gdb debugger, I have confirmed that the file is not being opened at all. I assume that I did not close the files properly, but I have a little knowledge of C++ yet (been learning it for only a week or so).

Looking forward to see what you can suggest reading/researching, yet I really would like to see a straightforward solution to this problem.


Solution

  • I assume that I did not close the files properly, [..]

    Yes, but that probably isn't the cause of the issue. The C++ way is to not close them explicitly. Due to RAII, the ifstream will close itself once it goes out of scope (i.e. when the enclosing function terminates).

    There are many reasons why a file could fail to open, including:

    • It doesn't exist.
    • Trying to open a read-only file in write mode.
    • The file is in use by another process. (Maybe you have it opened in an editor?)
    • Insufficient privileges (e.g. due to the file being protected).