fwrite/fread in C++

Mar 24, 2010 at 9:36am

Hi all,

Coming from a C background, I've been using fwrite and fread to write/read binary values (either a single value, or an array of values). Is there a preferred method for doing the same in C++?

Of course, I did notice that fread/fwrite documentation exists on this site, but printf as well -- even though streams are perhaps the preferred way of text I/O in C++ (I think).

Should I stick with fread/fwrite, or is there a preferred alternative that is "more C++"? Thank you!

Thank you!

Ray

Mar 24, 2010 at 9:51am
you can find what you're looking for in

http://cplusplus.com/doc/tutorial/files/
Mar 24, 2010 at 1:17pm
Yes, just make sure you open your files with the ios_base::binary flag.
1
2
3
4
ifstream f( "foo.txt", ios::binary );
f.read( ... );
int v = f.get();
...

Good luck!
Mar 25, 2010 at 3:18am
Hi,

Thank you both for your replies! Looks easy enough -- I'll give it a try.

Actually, I did a Google search for my problem and someone had asked this before on another message board and the reply was along the lines of "fread and fwrite still work fine for C++". Which is of course true...but if you're going to let others see your C++ code, you don't want to make it obvious that you were once a C programmer and can't change... :-)

Thank you for your help!

Ray

Mar 25, 2010 at 7:43am
evil c++-- jealousy...
Topic archived. No new replies allowed.