I'm studying C++, now I'm reading about working with files. As I have read, there is quite a lot of variants. So I wanna ask, what is the right way to work with files in C++? Using fstream(ifstream and ofstream)? I have read some opinions that fopen works much faster, so it is better to use it, but it will be no C++. Thanks for attention!
Asked
Active
Viewed 506 times
1
-
`fopen` is also a part of C++ (through C subset). :) – iammilind Oct 03 '11 at 08:49
-
7Please don't pay too much attention to things that say X is so much faster than Y. Most of the time it won't matter, but when it does, make your own judgement. Best approach is to use the right tool for the job. – Greg Hewgill Oct 03 '11 at 08:54
2 Answers
3
Use ifstream
and ofstream
when working in C++. It should not be much slower than FILE*
, but is much safer.

Community
- 1
- 1

Juraj Blaho
- 13,301
- 7
- 50
- 96
-
-
Safer than using `FILE*`. For instance you will never forget to call `close` because `fstream` closes automatically when out of scope. – Juraj Blaho Oct 03 '11 at 09:01
-
so it is safer only because it will sure release the resource? And in any way FILE* works faster. – Hate Oct 03 '11 at 09:21
-
@Hate: Is it not enough to to have automatic resource deallocation? I would say that is a huge benefit. There are also other benefits like reading `std::string` instead of `char *`. – Juraj Blaho Oct 03 '11 at 09:28
0
I agree with Juraj's assessment of i/ofstream vs. FILE*, I just wanted a word about memory-mapped files. In Boost.SpiritClassic, there's a lesser-known gem called a mmap_file_iterator:
http://www.boost.org/doc/libs/1_47_0/boost/spirit/home/classic/iterator/file_iterator.hpp
I believe that it will memory-map your file if you're in a windows or POSIX environment, and it is a RandomAccessIterator, rather than a Input/OutputIterator.
As for what method is "proper", it all depends on your application's requirements. It is definitely good to explore all of your options and compare the results along as many dimensions as you can conceive.

gred
- 612
- 1
- 8
- 15