Read from file, clear it, write to it - c++

I'm trying to read data from a text file, clear it, and then write to it, in that order using the fstream class.
My question is how to clear a file after reading from it. I know that I can open a file and clear it at the same time, but is there some function I can call on the stream to clear its contents?

You should open it, perform your input operations, and then close it and reopen it with the std::fstream::trunc flag set.
#include <fstream>
int main()
{
std::fstream f;
f.open("file", std::fstream::in);
// read data
f.close();
f.open("file", std::fstream::out | std::fstream::trunc);
// write data
f.close();
return 0;
}

If you want to be totally safe in the event of a crash or other disastrous event, you should do the write to a second, temporary file. Once finished, delete the first file and rename the temporary file to the first file. See the Boost Filesystem library for help in doing this.

Related

how to Read/Write multiple objects from file in C++?

When i try this writing multiple objects to file is done properly.
but while i try to Read multiple objects from file it show only data of last object.
Write Multiple objects to file:-
for(int i=0;i<n;i++)
{
s[i].getdata();
ofstream file("Simple.txt");
if(file.is_open())
{
cout<<"File created"<<endl;
file.write((char*)&s[i],sizeof(s[i]));
file.close();
}
else
{
cout<<"File not Open../"<<endl;
}
}
where, s is object
used in for loop as generating multiple objects.
When you execute ofstream file("Simple.txt"); you are opening a file in write mode.
And that you are doing for every iteration.
It means every time you write a file it is writing from beginning. ie, you are overwriting your file everytime.
You should try opening in append mode.
That might help.
Also as the first comment suggested, it is not a good idea to open and close a file in every iteration.
Hope this helps.
...
std::ofstream file;
file.open("Simple.txt" | std::ofstream::app);
...
You have to open the file in append mode.
You could also declare the file handle before the loop, and then just read in the values, then after the loop close the file handle.

Data isn't being saved in the text file (C++ Fstream library )

I've been trying to save the score of the player in the game in a text file, but it doesn't do so.
This is the code I'm using:
//some code above
std::fstream TextScore ("Ranking.txt");
// some code above
if (Player->getFinal(Map) == true)
{
TextScore.open("Ranking.txt", ios::out);
TextScore << Player->getPoints();
TextScore.close();
//some code below
}
Then I check the text file and nothing has been saved, the file is empty.
I would like to know what I'm missing or doing wrong.
Thanks in advance.
std::fstream TextScore ("Ranking.txt");
This opens the file, as if TextScore.open("Ranking.txt"), std::ios::in|std::ios::out) was called.
TextScore.open("Ranking.txt", std::ios::out);
This opens it again.
The combination is not going to work if the file already exists. The first open will succeed and the second one will fail. After that, all I/O operations will fail. Open it just once, either in the constructor or in a separate open call. The most idiomatic C++ way would be
{
std::fstream TextScore ("Ranking.txt", std::ios::out);
TextScore << Player->getPoints();
}
No need to close the file explicitly thanks to RAII.
Opening the same file twice is certainly going to cause problems. Move the definition of TextScore into the body of the if statement in place of the call to TextScore.open(). And then you can remove the call to TextScore.close(); the destructor will close the file.

How to clear a file in append mode in C++

I've a file on which I require multiple operations. Sometimes I just want to append data at the end of the file, sometimes I just want to read from the file, and sometimes, I want to erase all the data and write form the beginning of the file. And then, I again need to append data at the end of file.
I'm using following code:
ofstream writeToTempFile;
ifstream readFromTempFile;
writeToTempFile.open("tempFile.txt", ios::app | ios::out);
readFromTempFile.open("tempFile.txt", ios::in);
// Reading and Appending data to the file
// Now it is time to erase all the previous data and start writing from the beginning
writeToTempFile.open("tempFile.txt", std::ofstream::trunc); // Here I'm removing the contents.
// Write some data to the file
writeToTempFile.open("tempFile.txt", std::ofstream::app); // Using this, I'm again having my file in append mode
But what I've done doesn't work correctly. Please suggest me some solution in C++. ( Not in C)
The problem with the code is:
I wasn't closing the file before I called the method open again on it.
So, close the file before you re-open it with some different permissions.

clear data inside text file in c++

I am programming on C++. In my code I create a text file, write data to the file and reading from the file using stream, after I finish the sequence I desire I wish to clear all the data inside the txt file. Can someone tell me the command to clear the data in the txt file. Thank you
If you simply open the file for writing with the truncate-option, you'll delete the content.
std::ofstream ofs;
ofs.open("test.txt", std::ofstream::out | std::ofstream::trunc);
ofs.close();
http://www.cplusplus.com/reference/fstream/ofstream/open/
As far as I am aware, simply opening the file in write mode without append mode will erase the contents of the file.
ofstream file("filename.txt"); // Without append
ofstream file("filename.txt", ios::app); // with append
The first one will place the position bit at the beginning erasing all contents while the second version will place the position bit at the end-of-file bit and write from there.
If you set the trunc flag.
#include<fstream>
using namespace std;
fstream ofs;
int main(){
ofs.open("test.txt", ios::out | ios::trunc);
ofs<<"Your content here";
ofs.close(); //Using microsoft incremental linker version 14
}
I tested this thouroughly for my own needs in a common programming situation I had. Definitely be sure to preform the ".close();" operation. If you don't do this there is no telling whether or not you you trunc or just app to the begging of the file. Depending on the file type you might just append over the file which depending on your needs may not fullfill its purpose. Be sure to call ".close();" explicity on the fstream you are trying to replace.
Deleting the file will also remove the content.
See remove file.
You should create a function which clears all the data of the file and then run it.
void clear()
{
ofstream file("fileout.txt");
file<<"";
}

How to copy files in Visual C++?

I am using Visual C++. How to copy the content of this file to another file?
UINT32 writeToLog(wstring log)
{
wfstream file1 (LOG_FILE_NAME, ios_base::out);
file1 << log;
file1.close();
// want to copy file1 to file2
return 0;
}
What exactly do you want to do? If you need a copy of the data, you can read it in and write it back out again. If you really need a copy of the file, you have to use OS specific calls.
In many cases, reading in the file data and then writing it out again to a different file is a close enough approximation to a copy - like this:
ifstream file1(...);
ofstream file2(...);
std::copy(istream_iterator<char>(file1),istream_iterator<char>(),ostream_iterator<char>(file2));
However that really isn't a copy - it's creating a new file with the same contents. It won't correctly handle hard links or symlinks, it won't correctly handle metadata and it will only 'copy' the default file stream.
If you need a file copy on Windows you should call one of CopyFile, CopyFileEx or CopyFileTransacted depending on your exact requirements.
Standard C++ has no file copying facility, other than reading the file into memory and writing it out again to a different file. As you are using Windows, you can use the CopyFile function - other OSs have similar, OS-specific functions.
The above code from Joe Gauterin did not work for me. I was trying to copy a .tga image file, so maybe something about istream_iterator<char> screwed it up. Instead I used:
ifstream file1(...);
ofstream file2(...);
char ch;
while(file1 && file1.get(ch))
{
file2.put(ch);
}