ofstream driving me nuts
-
Hi, I have a class that needs to output data to a file. for this I defined a std::ofstream as a class member. However for some reasons I cannot get this to work. Writing to file works fine when I define a std::ofstream locally in a function, but for some reason it does not work when I use the std::ofstream as a class member. This is driving me nuts. example:
#include <fstream> class MyClass { public: MyClass() {}; virtuel ~MyClass(){}; void WriteSomething(); private: std::ofstream m_file; } void MyClass::WriteSomething() { CString str = "test\n"; std::ofstream file; // does not work. m_file.open("c:\\test.txt", std::ios::out); m_file.write(str, str.Getlength()); m_file.close() // does work. file.open("c:\\test2.txt", std::ios::out); file.write(str, str.Getlength()); file.close() }
-- modified at 17:00 Thursday 12th January, 2006 -
Hi, I have a class that needs to output data to a file. for this I defined a std::ofstream as a class member. However for some reasons I cannot get this to work. Writing to file works fine when I define a std::ofstream locally in a function, but for some reason it does not work when I use the std::ofstream as a class member. This is driving me nuts. example:
#include <fstream> class MyClass { public: MyClass() {}; virtuel ~MyClass(){}; void WriteSomething(); private: std::ofstream m_file; } void MyClass::WriteSomething() { CString str = "test\n"; std::ofstream file; // does not work. m_file.open("c:\\test.txt", std::ios::out); m_file.write(str, str.Getlength()); m_file.close() // does work. file.open("c:\\test2.txt", std::ios::out); file.write(str, str.Getlength()); file.close() }
-- modified at 17:00 Thursday 12th January, 2006When you say 'does not work', what does it do ? Does this only get called once ? Does any other code use the member variable ? Christian Graus - Microsoft MVP - C++
-
When you say 'does not work', what does it do ? Does this only get called once ? Does any other code use the member variable ? Christian Graus - Microsoft MVP - C++
The destination file is created, but remains empty. I have to say, I gave up and now use a CFile, which does use, but I still like to know why the ofstream does not work.
-
The destination file is created, but remains empty. I have to say, I gave up and now use a CFile, which does use, but I still like to know why the ofstream does not work.
Thats probably because of caching: The function's local stream is closed as the function exists so the file is flushed to disk and closed. On the other hand, the class member stream is not flushed so u c a file but no data. To check this u just have to flush the file explicitly. [I'd paste some code here but I use FILE*fh=fopen or CreateFile. Never c++ streams nor CFile]