Sections
You are here: Home Programming C, C++ etc. File append failure

File append failure

"ios::app" (append) doesn't

Not actually a conflict between CodeWarrior and gcc, this problem turned up simultaneously in both compilers. I inherited a program that repeatedly logged data to a file, first creating the file, closing it, and then opening it and closing it for each entry:

	fstream theFooFile;
	theFooFile.open (mFilePath, ios::app);
	theFooFile.close ();
	
	// ... later ...  
	
	fstream theBarFile;
	theBarFile.open (mFilePath, ios::app);
	theBarFile << theData << endl;
	theBarFile.close ();

Not efficient, but it worked properly and silently for a long time before suddenly not. Under both CodeWarrior and gcc, the created logfiles ended up empty. The exact problem is unclear but - at least for a plain fstream - the ios::app appears to truncate the file upon opening rather than appending the data. This may be simply corrected by changing all fstream to the more specific and appropriate ofstream to get:

	ofstream theFooFile;
	theFooFile.open (mFilePath);
	theFooFile.close ();
	
	// ... later ...
	
	ofstream theBarFile;
	theBarFile.open (mFilePath);
	theBarFile << theData << endl;
	theBarFile.close ();
Document Actions
Visitors
Locations of visitors to this page