Reputation: 29
I am making a program where I would like to check the first line of a .txt file for a specific string. If that string is tampered with or does not exist I would like to delete the content of the entire file to prevent tampering with the file. I know that it is possible to delete the contents of the file when opening it, but I cannot find a way to do so after checking the first line.
getline(infile, fLine);
cout<<fLine<<"\n";
if(fLine != "Line One"){
infile.clear();
outfile << "Line One\n";
}
Upvotes: 0
Views: 3212
Reputation: 33954
Just write nothing to the file by truncating it:
infile.close()
infile.open("file.txt", fstream::out | fstream::trunc);
infile.close()
note that this implementation will depend on your declaration of infile. If it is an ifstream
you will need to do this:
ofstream outfile;
outfile.open("file.txt", ofstream::out | ofstream::trunc);
outfile.close()
Upvotes: 4