fstrem.open() causes ERROR_ALREADY_EXISTS

hello, I wrote a simple logger, which should print last error through win32 Api function GetLastError. However, logger itself creates the last error and false feed back caused me a day.

_file.open("log.txt", std::fstream::out | std::fstream::trunc); this line generate ERROR_ALREADY_EXISTS log.txt is already exist, yes it does exist, I just want to override the actual one.


_file.open("log.txt", ios::app); this line is another problem, I just want to open the existing file and append to new text to it but this line generates the same error.

How can I do these operations without getting error ?

thank you for your replies.
closed account (zwA4jE8b)
are you trying to open it twice? or are those 2 different attempts?
This is the logger class
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#ifndef AMZ_LOGGER_H
#define AMZ_LOGGER_H

#include "amzPrerequisite.h"

namespace amz {

	class _AmzExport Logger {
	public: 

		static Logger* getLogger() {
			if(_logger == 0) {
				_logger = new Logger;
			}
			return _logger;
		}

		void log(String msg) {
            msg.append("\n");

			_file.open("log.txt", ios::app);
			assert(_file.is_open());

			_file.write(msg.c_str(),msg.length());
			_file.close();
		}

		~Logger() {
			_file.close();
		}

	protected:

		Logger() {
			// create a log file
			_file.open("log.txt", std::fstream::out | std::fstream::trunc);
			assert(_file.is_open());
			_file.close();
		}

	private:
		static Logger* _logger;
		FileStream _file;

	};

}

#endif
closed account (zwA4jE8b)
try declaring _file as ofstream _file; you might have to #include <iostream>
thank you for suggestion, but it didn't work :/
ERROR_ALREADY_EXISTS is not an error at all! Check out the CreateFile() function's documentation, which I guess is ultimately called by the C++ runtime under Windows (this is Windows, right?).

http://msdn.microsoft.com/en-us/library/aa363858(v=vs.85).aspx
Last edited on
Topic archived. No new replies allowed.