Sign in to follow this  
d000hg

Can I write to the same FILE with fprintf & fstream?

Recommended Posts

I'm writing a tracing utility class at work. The class must support a method which works like printf. I'd also like it to support the << C++ way of doing things. Is it possible that I can have either a FILE * or an fstream object, so that I can use both methods on the same file interchangeably? Or is it easier to have my Tracer::Output(char *str, ...) method just internally use the operator<<() method - I imagine it might be? EDIT: also, if I do fprintf to the same file in multiple threads, I think this is 'safe'. But is it possible that if two threads want to write at the same time, the two strings will get mixed up? If so, is the solution just to wrap my call to fprintf in a critical section? [Edited by - d000hg on June 7, 2006 5:44:42 AM]

Share this post


Link to post
Share on other sites
You won't be able to open the same file twice. The second call will fail. There *may* be a way of initialising an fstream with a FILE pointer but I'm not aware of it and I can't really see why you would want to to be honest.

If you synch_with_stdio, you can use printf and cout interchangably etc but I can't really see how this would work with a disk file.

Share this post


Link to post
Share on other sites
As far as I'm aware there's nothing stopping you opening the same file twice; however if you don't flush after every write multiple handles are not guaranteed to be synchronized correctly. As I understand it sync_with_stdio lets you do that, but it will hurt performance. I'm surprised somebody on here hasn't already pointed out the pitfalls of varargs functions, but if you want to do it that way I'd recommend using vsnprintf to get the output into a buffer and then writing it via whatever output function you choose - it's not that hard to get this to work correctly without any potential overflows, although it is slightly platform dependent. Alternatively you could use FILE pointers exclusively for IO and use a strstream to perform C++ style formatting.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this