ofstream doesn't work as a class member

I am trying to make my own file handler, but as always when i try to use std, there are problems. The exactly same code does work when the ofstream is local, but it doesn't work when it's a class member... I did some research and from what i saw, it should work.

this works:
int abc = 123;
std::ofstream test;
test.open("C:/Users/abc/Desktop/test.bin", std::ios::out | std::ios::binary| std::ios::app);
test.write((char*)&abc, sizeof(int));

this does not work:
int abc = 123;
m_test.open("C:/Users/abc/Desktop/test.bin", std::ios::out | std::ios::binary| std::ios::app);
m_test.write((char*)&abc, sizeof(int));
Last edited on
and where is m_test defined?

and what is the issue when it 'doesn't work'?
Hello Bamboo445,

Since you are new here and for future reference:


PLEASE ALWAYS USE CODE TAGS (the <> formatting button), to the right of this box, when posting code.

Along with the proper indenting it makes it easier to read your code and also easier to respond to your post.

http://www.cplusplus.com/articles/jEywvCM9/
http://www.cplusplus.com/articles/z13hAqkS/

Hint: You can edit your post, highlight your code and press the <> formatting button. This will not automatically indent your code. That part is up to you.

You can use the preview button at the bottom to see how it looks.

I found the second link to be the most help.



The bit of code that you posted is totally out of context and you have not shown what you have done.

It is best to post the whole program that can be compiled and testted or at at least enough of the program that can be compiled and demonstrate the problem.

If there is an input file include this so everyone can be using the same information.
javascript:editbox1.editSend()
Andy
m_test was in private section of the class, the code is in the class constructor. The issue is that the file is created, but no data output..

Anyways, nevermind, the issue was the lack of close function.. In order to operate the file has to be closed, i was thinking when i am completely done with that file, then i will just close it. Looks like the local variable does execute close() in the destructor, that's why it was working.
Looks like the local variable does execute close() in the destructor, that's why it was working.


yes. and .close() does a buffer flush.

I/O is buffered. When you do write, it will write to the buffers. At some point the OS will flush these buffers to disk. If you're checking the physical file contents between a write and a close, then yes it might appear that the write hasn't written anything.

Also there's .flush() which will force content to be written from buffer(s) to the disk.
Last edited on
Topic archived. No new replies allowed.