File write, without deleting old lines? - c++

I currently have this to write to a file in my program. I have all the variables ready to put into the file I just have an issue.
void fileWrite(int score)
{
ofstream file;
file.open("MathGen.txt");
file << "The score was: " << score;
file.close();
}
So when this runs it creates the files and writes the score perfectly fine. But if I re-run the program and get a new score it will overwrite the old score. Is there any way to stop this from happening? I know in python you could use file write functions such as "a+". But that doesn't work here.

You should use append mode on your file in ofstream.open:
file.open("MathGen.txt", std::ofstream::app);
More info on this method is here

Related

Adding a new line to existing txt file in c++

As a tutorial I've been a question to add new line to an existing file with a list of items. i've tried numerous ways to add it. no luck yet
ofstream outdata;
ifstream indata;
indata.open("fruits.txt");
outdata.open("fruits.txt");
if(indata.is_open()){
std::string fruit;
std::cout << "enter a fruit to list "<<endl;
std::cin >> fruit;
outdata << "\n" << fruit << "\n" << endl;
indata.close();
outdata.close();
return 0;
}
This part of the code is supposed to ask the user to enter a value. Its supposed to be stored as new line without deleting the existing line. But here I'm. I've seen a few answers here. but can't find anything understandable.
When you open a file for writing its contents are immediately removed, if the file already exists.
outdata.open("fruits.txt");
You opened the same file for writing here. This is before your code tries to read anything from the same file (I don't actually see anything in your code that tries to read it, I presume you left that part out). And by the time you get to the file it's already empty and there's nothing to read any more from it.
You have three choices:
Read the entire contents of the file into your program, and only then open it for writing and write out the new contents.
Open a different file for writing. After finishing reading and writing both files, and closing them, rename the new file to the original file.
Open the file for appending:
outdata.open("fruits.txt", std::ios::app);
It's not necessary to open it for reading, this will add to the end of the file, instead of overwriting it.

How can i solve an issue in writing data in specific file in my clr project?

I am trying to add some data to a specific file in my project. I am doing that in the function below.
void Files::write_employee(employee employeeObject)
{
fstream infile;
infile.open("employeeFile.txt",ios::in|ios::out|ios::app);
string record;
char delimiter='#';
record=employeeObject.get_id()+delimiter;
record+=employeeObject.get_name()+delimiter;
record+=employeeObject.get_password()+delimiter;
record+=employeeObject.get_age()+delimiter;
record+=employeeObject.get_gender()+delimiter;
record+=employeeObject.get_MaritalStatus()+delimiter;
record+=employeeObject.get_ministryName()+delimiter;
record+=employeeObject.get_departmentName()+delimiter;
record+=employeeObject.get_salary()+delimiter;
record+=employeeObject.get_photoPath()+delimiter;
record+=employeeObject.get_photoFileName()+delimiter;
if (infile.fail())exit(1);
else {infile<<record;
infile.close();}
}
This function explains how to add data to my file through save the entered data
in an object and save this values in string record and push it to the file.
The big problem is my file which I am trying to add data in, not created yet.
and I don't know why.
thanks in advance.
You use infile whereas you are outputting to file. While this does not affect the program code, it makes no sense and break your program readability. Use outfile instead.
Remember that it is just like cout << and cin >> for the standard I/O.
Also, try not to use ios::in when your purpose is only to output to the file and vise versa.
According to std::fstream::open example at cplusplus.com, your code is correct and the file must be created. First try to specify an absolute file path to a location that you have write access. If it does not work, print the error message using the following line of code:
cerr << "Error: " << strerror(errno);

How can I write to a .csv file multiple times and keep the previous data using C++?

As of now I am doing this:
std::ofstream file;
file.open("test.csv");
file << "Test case" << std::endl;
file.close()
The problem is the .csv file will get overwritten with new data, each time a programme is launched. So in this case each time I run the programme I would get one line of the text "Test case" instead of having this line added to the .csv file. Is there a way to keep the data consistent and just add them to the same file, while keeping the previous data, each time I run the programme?
You can specify a second parameter to open, for example file.open("test.csv", ios_base::app).
http://www.cplusplus.com/reference/fstream/ofstream/ofstream/
http://www.cplusplus.com/reference/fstream/filebuf/open/

How to have a text file created based on user input C++

I'm fairly new to C++. I'm creating a code that will input a file and output the results in an output file, and using stacks and junk.
But what i want to do is create a file based on a user input. Asking the user (when a file doesn't exist in a specific directory) if they would like to create that empty file. I've done this on C# using Directory and Dictionary, but C++ isn't really clicking for me. Here's the snippet of my code (I'm not going to paste 200+ lines for one thing) and where i want to do. Ignore the comments. It's just to keep track of what I'm doing.
if (file.is_open()) //if the file is open (and works)
{
string output;
cout << "Please enter the full directory of the file you would like to have the results in" << endl;
cin >> output;
output.c_str();
file_result.open(output); //open the results file for checking answers
while (file_result.fail())
{
cout << "This file does not exist. Would you like to make one?" << endl;
}
As you see, where I ask the user if they would like to make that file is where i would want this to be.
Any help would be lovely! Transitioning from C# to C++ was a bad idea.
You can open a file for writting (in append mode) in this way:
std::ofstream ofs;
ofs.open (output.c_str(), std::ofstream::out | std::ofstream::app);
ofs << " more lorem ipsum";
ofs.close();
More information about file operations can be found here:
http://www.cplusplus.com/reference/fstream/ofstream/open/
The most basic way to create a file based off of user input is this, You should how ever include checks to make sure the path is valid and that no file exists etc.. I only have time to show you how to do this.
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
ofstream outFile;
string path;
cout << "Please enter the full path for your file: ";
getline(cin, path);
outFile.open(path);
return 0;
}
What's happening here is quite simple the user inputs the full path (C:\Hello.txt) it's read by getline(cin, path) and is stored in path.
outfile then creates that file.
Please make sure you add checks to validate no file with that name already exists etc.. I'll update this later with a better example but this will create a file for you

Avoid contents of an existing file to be overwritten when writing to a file

I am trying to make a game that implements high scores into a .txt file. The question I have is this : when I make a statement such as:
ofstream fout("filename.txt");
Does this create a file with that name, or just look for a file with that name?
The thing is that whenever I start the program anew and make the following statement:
fout << score << endl << player;
it overwrites my previous scores!
Is there any way for me to make it so that the new scores don't overwrite the old ones when I write to the file?
std::ofstream creates a new file by default. You have to create the file with the append parameter.
ofstream fout("filename.txt", ios::app);
If you simply want to append to the end of the file, you can open the file in append mode, so any writing is done at the end of the file and does not overwrite the contents of the file that previously existed:
ofstream fout("filename.txt", ios::app);
If you want to overwrite a specific line of text with data instead of just tacking them onto the end with append mode, you're probably better off reading the file and parsing the data, then fixing it up (adding whatever, removing whatever, editing whatever) and writing it all back out to the file anew.