I'm new to file I/O in C++ and have encountered a problem. My program checks to see if file "projectdb.txt" exists. If it does, it uses its data to populate an array. If it doesn't exist, it is supposed to create the file. This is where I am having the problem.

Here's the code:

fstream dbfile(DB_FILE_NAME);
	
	if (dbfile.is_open()) {
		// functions are performed here.
	} else {
		cout << "You have no database file. Creating one now..." << endl;
		dbfile << "# This is your database file.\n";

		// Lots of irrelevant code omitted

		dbfile.close(); // This is only here because I was trying to see if it would cause the file to write. It isn't writing when it closes, so I'm clearly having problems with this.
	}

Why am I having problems creating the file? Keep in mind I'm new to this. Thank you!

Can you do something like

ifstream dbfile(DB_FILE_NAME);
	
if (dbfile.is_open()) {
	// functions are performed here.
} 
else {
        ofstream newdbfile(DB_FILE_NAME);
	cout << "You have no database file. Creating one now..." << endl;
	dbfile << "# This is your database file.\n";

	// Lots of irrelevant code omitted
	newdbfile.close(); // This is only here because I was trying to see if it would cause the file to write. It isn't writing when it closes, so I'm clearly having problems with this.
}

So if a file is not found you create a new one using ofstream. There might be a better way to do this may be.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.