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.
Related
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);
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
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
I have a text file where I want to write. I want to keep the file content always. I want to write following a "FIFO" (last write always on the top line of the file).
I try using fout.open("filename"); with ate mode to keep file content, after that use seekg(0) trying to take back writing cursor to the begining of the file. Didn't work.
The unique way I found to do that I think it's so time-expensive, copy all the file content to a temporary file. Write want I want to write and after that write the content of the temp file at the end of the target file.
There must be an easy way do this operation?
Jorge, no matter what you will have to rewrite the entire file in memory. You cannot simply keep the file where it is and prepend memory, especially since it's a simple text file (maybe if there was some form of metadata you could...)
Anyways, your best chance is to flush the old contents into a temporary location, write what you need and append the old contents.
I'm not sure what you're asking for. If you want to add a
line to the beginning of the file, the only way is to open a
new, temporary file, write the line, copy the old file into
after the new line, then delete the old file and rename the
temporary.
If the original line has a fixed length, and you want to replace
it, then all you have to do is open the file with both
ios_base::in and ios_base::out.
First, you should realize that files are historically streams, i.e. they can only be read and written in one direction. This comes from the times when files were stored on tapes, which could move in one direction (at that time).
However, if you only want to prepend, then you can just store your file backwards. Sounds silly? Maybe, but this would work with just a little overhead.
Apart from that, with current OS's you will need to make a copy to prepend. While files are not streams anymore, and can be accessed randomly on a harddisk, they are still made to grow in one direction. Of course you could make a filesystem, where files grow in both directions, but I have not heard of one.
With <fstream> you may use the filebuf class.
filebuf myfile;
myfile.open ("test.txt", ios::in | ios::out);
if (!myfile.is_open()) cout << "cannot open" << endl;
myfile.sputn("AAAA", 4);
myfile.close();
filebuf myfile2;
myfile2.open ("test.txt", ios::in | ios::out);
if (!myfile2.is_open()) cout << "cannot open 2" << endl;
myfile2.sputn("BB", 2);
myfile2.close();
write to a string in order you want, then flush to the 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.