void save_file(string fileName)
//saves the file to file fileName.txt
{
fstream myfile(fileName);
if (myfile.is_open())
{
myfile << "Blah\n";
myfile.close();
}
else cout << "Unable to open file";
}
Basically I want a function that takes a string fileName and uses that to create a new text document. How would I do that?
The user will choose the filename, so he can save the file as hello.txt or whatever.
also, make sure MyFile.txt is available in the folder where exe is created.
you can use ios::in | ios::out | ios::app as second arg to append the file.
void save_file(string fileName)
//saves the file to file fileName.txt
{
fstream myfile;
bool exists;
//check whether the file exists
myfile.open(fileName.c_str(),ios::in);
if (myfile.is_open())
{
exists=true;
myfile.close();
}
else
{
exists = false;
}
//if not create it
if (!exists)
{
myfile.open(fileName.c_str(),ios::out);
myfile.close();
}
//open for reading and writing
myfile.open(fileName.c_str(),ios::in|ios::out);
myfile << "Number of records: " << record_size-1 << endl;
for(int i = record_size-1; i > 0; i--)
{
myfile << student_records[i].name << ": " << student_records[i].score << endl;
}
myfile << endl;
myfile.close();
}
But there's just one more hiccup (sorry) -- it's that when I run it for the first time and the file doesn't exist, the file WILL be created but will be entirely empty. If I run it and the file does exist, then it works fine. Can someone point out what's wrong?
But there's just one more hiccup (sorry) -- it's that when I run it for the first time and the file doesn't exist, the file WILL be created but will be entirely empty. If I run it and the file does exist, then it works fine. Can someone point out what's wrong?
My bad... When you check if the file exists and it doesn't exist some error flag of myfile is set and therefore it can't be used for input or output. Just modify your code like this and it should be fine:
1 2 3 4 5 6 7 8 9 10 11 12
//check whether the file exists
myfile.open(fileName.c_str(),ios::in);
if (myfile.is_open())
{
exists=true;
myfile.close();
}
else
{
exists = false;
myfile.clear(); //<- add this here
}