You are mixing C and C++ in a very unhealthy way, I fear.
First, I heartily recommend using std::string instead of a char*, believe me, you'll have far less troubles.
Second, you should beware of pointers: they may point, if you are not careful, to places in memory that no longer host any "live" object.
I would propose the following code:
void execute(std::ostream& out) { out << "test\n"; } // execute int main(int argc, char* argv[]) { if (argc == 1) { execute(std::cout); return 0; } std::string filename = argv[1]; filename += ".log"; std::ofstream file(filename.c_str()); execute(file); return 0; }
Which illustrate how to avoid the two pitfalls you fell into:
- using
std::string I avoid allocating a statically sized buffer, and thus I do risk a buffer overflow. Furthermore operations are so much easier. - using a function to hoist out the printing logic, I do away with the pointer and the subtle issues it introduced.
It is unfortunate that std::string and std::fstream (and consorts) do not mix so well, at the moment. Historical defect... fixed in C++0x if I remember correctly.