Can't clear file before writing to it with fstream

Hello, all! I am programming a login authenticator and password management system using sha256 and salted password hashing. I have implemented a Binary search tree to store the user login information as nodes in a BST tree. Currently, I am having problems writing to the user text file for storing the user data.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
userFile.open("dataUsers.txt", fstream::trunc);
	userFile.close();
	userFile.open("dataUsers.txt", ios::app);
	if (userFile.is_open())
	{
		while (!myQueue.isEmpty())
		{
			popNode = myQueue.pop();
			userFile << popNode->user << endl;
			userFile << popNode->passHash << endl;
			userFile << popNode->salt << endl;
		}
	}
	userFile.close();


The program outputs correctly, but it doesn't clear the previous contents of the text file. I have read that opening a file with the fstream::trunc flag should clear the contents of the file when you close it, but it doesn't seem to be working. Any help is much appreciated! Thankyou!
Maybe it doesn't replace the file because you wrote no data to the file. Not sure why you are using ios::app. Will it not work if you simply remove line 2 and 3?
Last edited on
Please show how userFile was defined.

Perhaps it never opened correctly or it was already open you really should check if that open succeeded.

Do you realize that if you use the ios::trunc flag with an fstream you must also use the ios::out flag as well, just using the trunc flag by it's selfs puts the stream in a fail state. Also it really doesn't make much sense to open the file to truncate then close the file and reopen with the ios::app flag.

Lastly if you happen to be using a pre-C++11 compiler you need to be careful when reusing the streams since just opening and closing the stream doesn't reset the stream state.

Last edited on
I am using a c++11 compiler, but I will still be careful!
The userFile is defined in code like this
 
fstream userFile;

I tired using ios::trunc | ios::out , but now will only write to the program the first time it is opened, and then fails for every other time.
1
2
3
4
5
6
7
8
9
10
11
12
userFile.open("dataUsers.txt", fstream::trunc | ios::out);
	if (userFile.is_open())
	{
		while (!myQueue.isEmpty())
		{
			popNode = myQueue.pop();
			userFile << popNode->user << endl;
			userFile << popNode->passHash << endl;
			userFile << popNode->salt << endl;
		}
	}
	userFile.close();
What do you mean by it fails?

How do you know it is failing?

By the way it seems to work as I would expect. Every time you open the file it deletes the contents and starts over.

Topic archived. No new replies allowed.