Home

fstream

fstream is a component of the C++ standard library that provides file input and output streams. It is defined in the <fstream> header and is based on the generic iostreams framework. The library supplies three types: std::ifstream for input from files, std::ofstream for output to files, and std::fstream for both input and output from files. These types are aliases of the templated std::basic_fstream<char> specialized for char.

Opening files: A file stream is opened by constructing it with a filename and an opening mode,

Reading and writing: Data are transferred using the extraction operator (>>) and insertion operator (<<), as well as

Error handling and text vs binary: Streams maintain state flags such as goodbit, eofbit, failbit, and badbit.

Use in practice: fstream is widely used for reading and writing configuration files, logs, and data interchange.

---

or
by
default-constructing
and
calling
open.
Common
modes
include
std::ios::in
for
reading,
std::ios::out
for
writing,
std::ios::app
to
append,
and
std::ios::trunc
to
truncate
existing
content.
For
binary
data,
add
std::ios::binary.
Modes
can
be
combined;
for
example,
std::fstream
f("data.dat",
std::ios::in
|
std::ios::out
|
std::ios::binary).
member
functions
read
and
write.
For
random
access,
use
seekg/seekp
and
tellg/tellp.
It
is
common
to
check
the
stream's
state
with
if
(fs)
or
fs.good(),
and
to
verify
whether
opening
succeeded
with
is_open()
after
open()
or
construction.
Exceptions
can
be
enabled
via
exceptions()
to
throw
on
errors.
In
text
mode,
some
platforms
perform
newline
translation;
binary
mode
avoids
translation.
When
using
ifstream/ofstream/fstream,
you
may
need
to
call
close()
to
release
resources,
especially
before
re-opening
a
file.
It
integrates
with
the
standard
C++
iostreams
and
supports
locale,
formatting,
and
synchronization
features
as
part
of
the
standard
library.