I made a function that alters a lone value in a text file. However, when I run my program I get an error indicating that the file was never opened.
I do not think the logic in my program is wrong, so my second thought was that my text was going to be in the wrong file (I’ve specified the location to the text file in the first line of the function).
So, I’m not sure where I have gone wrong, and it must be so silly and simple for me to spot.
Can anyone point it out? I need a second set of eyes.
void leaderboard(double percInc, int currChips, int oldChips) {
// compare old high score to new one
ifstream file("C:\C++\ReturnSum\x64\Debug\leaderboard.txt");
if (!file.is_open()) {
cerr << "Error" << endl;
return;
}
int oldScore;
file >> oldScore;
file.close();
// write new highscore
if (percInc > oldScore) {
ofstream file2("leaderboard.txt");
if (!file2.is_open()) {
cerr << "error";
return;
}
file2 << percInc << endl;
file2.close();
cout << "NEW HIGH SCORE";
}
else {
cout << "No high score today. ";
}
}
>Solution :
Your file path string contains unescaped \ characters. You need to escape them.
Also, you are opening the file for reading using an absolute path, but then opening the file for writing using a relative path. Your working directory may not be what you are expecting, causing you to end up trying to write to a file that doesn’t exist or you don’t have access to.
Define the file path in a separate variable that you can then use for both stream constructors.
Try this instead:
void leaderboard(double percInc, int currChips, int oldChips) {
string filename = "C:\\C++\\ReturnSum\\x64\\Debug\\leaderboard.txt";
// alternatively:
// string filename = R"(C:\C++\ReturnSum\x64\Debug\leaderboard.txt)";
// compare old high score to new one
ifstream infile(filename);
if (!infile.is_open()) {
cerr << "Error opening file for reading" << endl;
return;
}
int oldScore;
if (!(infile >> oldScore)) {
cerr << "Error reading file" << endl;
return;
}
infile.close();
if (percInc <= oldScore) {
cout << "No high score today." << endl;
return;
}
// write new highscore
ofstream outfile(filename);
if (!outfile.is_open()) {
cerr << "Error creating file for writing" << endl;
return;
}
if (!(outfile << percInc << endl)) {
cerr << "Error writing file" << endl;
return;
}
outfile.close();
cout << "NEW HIGH SCORE" << endl;
}