Append to a File with fstream Instead of Overwriting - c++

I'm trying to create a basic highscore system for a project I'm working on.
The problem I'm having is, although I write the names into my main they just overwrite the previous.
Currently I have this:
void ManagePoint::saveScore(string Name, int Score)
{
ofstream newFile("scorefile.txt");
if(newFile.is_open())
{
newFile << Name << " " << Score;
}
else
{
//You're in trouble now Mr!
}
newFile.close();
}
and for testing I'm adding them like so:
runner->saveScore("Robert", 34322);
runner->saveScore("Paul", 526);
runner->saveScore("Maxim", 34322);
On load display all that will appear is Maxim's score, how can I loop through and save them all, or append all or something?

You need to open the file with the append mode:
ofstream newFile("scorefile.txt", std::ios_base::app);
There are various other modes too.

Related

Have user type file they want read & appending filenames C++

Disclosure: I am a student right now, so if you see any bad habits in my code, feel free to point them out. I have questions about both the ofstream and ifstream portions of my code.
In the ofstream, the user can create their own shopping list and name it (which will end up being the file name). Once their list is created, the file will save with the data.
Here my question: How do I automatically assign a file type to a file a user named? Here is my current code for it:
void createList(double price[100], double quantity[100], string item[100], double tax, int list_size) {
ofstream saved_list;
string listname;
string fileApplicator = ".txt";
cout << "What would you like to save this list as?: ";
getline(cin, listname.append(fileApplicator));
saved_list.open(listname.c_str());
As for the ofstream part of my code, I want the user to be able to select which file they want read based on the name of the file.
Here's my question: When I run the code, the file fails to open every time. I have a current file saved as safeway.txt but it will not open when I attempt it. Here is the code for it:
void reviewList(void) {
ifstream saved_list;
string listname;
string fileApplicator = ".txt";
char viewAnother = 'Y';
do {
cout << "Which list would like to open: ";
getline(cin, listname.append(fileApplicator));
saved_list.open(listname.c_str());
if (saved_list.is_open()) {
......//other code
}
cout << "Would you like to view a different list (Y/N): ";
cin >> viewAnother;
viewAnother = toupper(viewAnother);
if (viewAnother == 'N')
break;
}
else {
cout << "List not found. Please try again.\n";
}
} while (viewAnother == 'Y');
}
Solution to this problem:
getline(cin,listname.append(fileApplicator)); is the error. The append needs to be processed AFTER the getline, like this:
getline(cin,listname);
listname.append(fileApplicator);
This will allow the user to not only name a file and have it automatically saved as the programmer's desired file type but will also automatically select the desired file to be read without the user needing to enter the extension (at least on Windows OS's). I.E.: User can enter "Filename" rather than "Filename.txt".
Thank you #user4581301 and #drescherjm for helping to solve this issue!

Settings in c++ with file .txt

I would like to make a read and write file in c++. I would also like the information i write be a string. so then i can read that string from the file and see the value. Im gonna use this sort of like a settings file where the program can read your settings that you've used and apply them without having to reconfigure the program everytime. In small here's what i got:
int main()
{
std::string tortilla = "tacos";
std::string godast = "pizza";
std::ofstream MyFile;
MyFile.open("1.txt");
MyFile << tortilla;
MyFile.close();
std::ifstream ReadFile("1.txt");
while (std::getline(ReadFile, tortilla))
As you see the code is not done yet by far but i just want to learn this element for now. Thank you in before.
EDIT: Here i want the output of reading "tortilla" to be tacos. So the string is intact troughout
To output the content of tortilla add:
{
std::cout << "tortilla is " << tortilla << std::endl;
}
And iostream must be included for std::cout. HTH.

ofstream creating file but not writing to it in C++

I am writing an MFC program that has a dialog with an "Export" button that will take all of the data that has been entered into the file and export it to a .txt (at some point I want to change this to a .msg file...but that's a question for another day).
However, when I click the button, it creates the file but doesn't write anything inside the file. For testing, I removed everything except just a simple literal string and even that isn't printing. Here is the current code for that event: The myfile.flush() statement is leftover from when I had a loop that I was trying to print to the file.
void CEHDAHTTimerDlg::OnBnClickedExport()
{
// in this function, we want to export the items to a text file
std::ofstream myfile("TodayTime.txt");
myfile.open("TodayTime.txt");
if (myfile.is_open())
{
myfile << "The average call time is ";
myfile.flush();
myfile.close();
}
else
{
SetDlgItemText(IDC_EXPORT, L"Export Unsuccessful! -- No File");
}
}
Is there anything you all can think of that could be causing this? I've been at it for a few hours trying different things, like utilizing a myfile.write() function instead. I've searched a lot around here, reddit, and google in general trying to find out why this isn't writing.
I appreciate your help.
EDIT:
Okay, calling the myfile constructor the way that I did, by including the file name, went ahead and did what open file would have done
Thanks for your help!
commenting out the redundant "open" solves it.
#include <iostream>
#include <fstream>
int main()
{
// in this function, we want to export the items to a text file
std::ofstream myfile("TodayTime.txt");
// myfile.open("TodayTime.txt");
if (myfile.is_open())
{
myfile << "The average call time is ";
myfile.flush();
myfile.close();
}
else
{
std::cerr << "didn't write" << std::endl;
}
}
I strongly suspect that you're invoking undefined behaviour by opening and already-open stream.
Here is the explanation:
The call to myfile.open("TodayTime.txt"); will fail because the stream is already associated with the file, setting the failbit.
The call to is_open() will succeed, as the file is open.
Then the call to streaming operator << will fail (because of the failbit).
this is because myfile << "The average call time is "; not working
to fix that
std::ofstream myfile;
myfile.open("TodayTime.txt",std::ios:app) //app for appending you can use trunc for
//truncating file
//for flushing content's of existing file use myfile.flush();
if (!data_pack.is_open())
{
std::cerr << "unable to open the file for writing";
}
myfile << "some stuff tho write you can replace the string with variable"
<<std::endl; //for next line
//at last close file
myfile.close();

ofstream does not create file when running with CLion using CMake

I have this code to create a file, when I run it with CLion it prints out to the console but does not create file, how can I fix this? thanks
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream log_file;
log_file.open("sample23.txt");
if (log_file.is_open())
std::cout << "Open";
log_file << "stuff" << endl;
log_file.close();
return 0;
}
The file may be created into another directory (the working directory).
You can find that location (and change it if needed) as indicated here:
How do I change the working directory for my program
make sure to flush before closing because file is empty
try this out
ofstream f;
f.open( "sample.txt", ios::out );
f << flush;
f.close();
3 things here:
1.) In order to output to another file, you must make another variable like this:
ifstream someoutputfile;
someoutputfile.open("filename");
2.) you actually must make another variable to be "placeholder" of sorts that will automatically assign the first thing your file finds and assigns that to. This may depend on what datatype (int, double, string etc) your input file consists of. Instead of:
log_file << "stuff" << endl;
you can do something like this...
// if my input file is integers for instance..
int data = 0;
log_file >> data;
This can also work for if your file contains multiple data types.
ex:
// if I have two different data types...
string somebody;
int data = 0;
log_file >> data >> somebody;
3.) to output your file data to the screen, just follow a similar way as the example in #1.
someoutputfile << data << somebody << endl;
in addition, dont forget to close the data of BOTH your input and output files:
someoutputfile.close()
Hope that helps in some way :)

How to "select" current directory?

I am writing a proportion calculator. At the beginning of the program, it loads a ascii text art picture from a .txt in the same folder.
Here is how I am doing it:
//Read picture
string line;
ifstream myfile("/Users/MYNAME/Desktop/MathScripts/Proportions/Value Finder/picture.txt");
if (myfile.is_open()) {
while (!myfile.eof()) {
getline(myfile, line);
cout << line << endl;
}
myfile.close();
} else cout << "Unable to load picture!!!" << endl;
//Finish reading txt
I heard how if the .txt is in the same folder, that you can just use the name and not have to say the directory. Meaning instead of
/Users/MYNAME/Desktop/MathScripts/Proportions/Value Finder/picture.txt
I could just use "picture.txt". That doesn't work for me, and I want the user to be able to move around the "Value Finder" folder without having to edit any code.
I am on Mac and I am using CodeRunner; anything odd?
Please do not tell me to make sure that picture.txt is in the same folder as my code. It is.
In order to open picture.txt without using a fully qualified path it has to reside in the current working directory. When an IDE launches an application it it sets the current working directory to the same one the application resides in. If picture.txt resides in a different directory than the application you will not be able to open it with just it's name. If you need to get the current working directory you can call getcwd like so.
char temp[MAXPATHLEN];
getcwd(temp, MAXPATHLEN);
If you want to allow the user to specify which directory picture.txt is in you can let them pass an argument on the command line. You can then create a fully qualified path with the supplied directory and the picture filename.
int main(int argc, const char **argv)
{
// Add some logic to see if the user passes a path as an argument
// and grab it. here we just assume it was passed on the command line.
const string user_path = arg[1];
//Read picture
string line;
ifstream myfile(user_path + "/picture.txt");
if (myfile.is_open())
{
while (!myfile.eof()) {
getline(myfile, line);
cout << line << endl;
}
myfile.close();
}
else
{
cout << "Unable to load picture!!!" << endl;
}
//Finish reading txt
return 0;
}
Now you can do something like this:
myapp "/user/USERNAME/Desktop/MathScripts/Proportions/Value Finder"
and it will look in that directory for the picture.txt file. (Quotes are required because there is a space in the pathname).
Note: You can call setcwd() to change the current working directory of the application.