filebuf object question

Is it possible and safe to declare a filebuf object like this?
1
2
filebuf fi;
fi.open("something.txt", ios::in | ios::binary);


or must I do something like this:
1
2
3
4
5
ifstream is;
filebuf * fb;

fb = is.rdbuf();
fb->open ("test.txt",ios::in);


I tried googling but all of the results so far take the second route, hence making me wonder if I can just declare a new object and use it? If the answer is yes, does the same apply to text mode as well, or only binary mode?

And what's really the different with the two ways?

Thanks in advance.
What do you intend to do with the filebuf?

The difference between a binary file and a text file is the text file is expected to have a sequence of characters terminated by a new line marker/end of line marker. Methods like getline/gets read upto the end of line. Binary mode places no interpretation on the file and just deals with sequences of bytes with read/write.
I have a large binary file and want to read its content as fast as possible. So far it seems the sgetn() method is what I need (it's the the fastest compared to cin.read() and fread(), based on my test files), but I don't know if it's safe to just declare the object like that and if so then why should I bother declaring an ifstream first, like in the second example?
I thought it might be something like that. You don't need go directly to the filebuf.

If it's a binary file, just use read (or write) in multiples of the OS block size (4K?).
filebuf got me the best write/read speed since it's low level (cin.read() is still high level, and fread() is not as fast as filebuf). What I'm not sure about is how declaration should be done.

Is it
1
2
filebuf fi;
fi.open("something.txt", ios::in | ios::binary);

or
1
2
3
4
5
ifstream is;
filebuf * fb;

fb = is.rdbuf();
fb->open ("test.txt",ios::in);

or
1
2
filebuf* fi = new filebuf();
fi->open("something.txt", ios::in | ios::binary);


Which is considered the best practice and why?
bump
OP wrote:
filebuf got me the best write/read speed since it's low level...

Would you mind explaining your metric? You should not see a speed difference between these two once you've compiled your program. You should be fine declaring a filebuf object as is, all ifstream does is add some functionality from ios_base, this functionality is REALLY useful stuff like end of file checking, but if you know for a fact that you aren't going to use it then I guess it doesn't matter.

Why would you ask this question? Why wouldn't you just try it?
Topic archived. No new replies allowed.