C++ Reference ยท Strings and I/O
C++ std::fstream class
Reference for std::fstream, the read-and-write file stream: open modes, seekg and seekp, tellg, in-place updates, closing, and how it relates to ifstream and ofstream.
std::fstream (header <fstream>) is a file stream that can both read and write the same file. Together with std::ifstream (input only) and std::ofstream (output only) it makes up the file stream family. Each one is an ordinary iostream, so everything you know from cin and cout (<<, >>, getline, manipulators, stream states) works the same on a file.
A file stream owns the file handle. It opens the file in its constructor or in open() and closes it in its destructor, so the usual pattern is to declare it in the smallest scope that needs it. fstream also keeps separate read and write positions in one file, which you move with seekg and seekp.
#include <fstream> std::fstream file("data.txt", std::ios::in | std::ios::out); if (!file) { // the file could not be opened }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.
Syntax
std::fstream f; std::fstream f(const char* filename, std::ios_base::openmode mode = ios::in | ios::out); std::fstream f(const std::string& filename, std::ios_base::openmode mode = ios::in | ios::out); std::fstream f(const std::filesystem::path& p, std::ios_base::openmode mode = ios::in | ios::out); void open(const char* filename, std::ios_base::openmode mode = ios::in | ios::out); bool is_open() const; void close(); std::istream& seekg(pos_type pos); // move the read position std::istream& seekg(off_type off, std::ios_base::seekdir dir); std::ostream& seekp(pos_type pos); // move the write position pos_type tellg(); pos_type tellp();
| Name | Description |
|---|---|
filename / p |
Path of the file. Relative paths use the program's current directory. |
mode |
A combination of in, out, app, ate, trunc, binary. |
pos, off, dir |
Absolute position, or an offset from std::ios::beg, cur or end. |
Open modes: in read; out write (truncates an existing file unless in or app is also set); app every write goes to the end; ate start at the end after opening; trunc discard existing contents; binary no newline translation. For fstream, the mode in | out requires the file to exist, in | out | trunc creates a new empty one.
Returns: the constructors and open do not return anything; the stream is in a failed state if the open did not work. is_open() is the explicit check. tellg and tellp return -1 if the stream has failed.
Errors / undefined behavior: I/O errors do not throw by default. Enable exceptions with f.exceptions(std::ios::failbit | std::ios::badbit) if you prefer that style. Reading and writing alternately on an fstream requires a seekg/seekp (or flush) between the two operations; skipping it is undefined behavior in the C++ standard.
Usage notes
- Check the open.
if (!f)orf.is_open()right after constructing. A wrong path or missing permission otherwise shows up later as mysteriously empty reads. - Alternate carefully. Switching from reading to writing on the same stream needs a seek in between. Prefer separate
ifstreamandofstreamobjects when you can; see ifstream and ofstream. - Clear before seeking. After reading to the end,
eofbitandfailbitare set and aseekghas no effect on some implementations. Since C++11seekgclearseofbitfirst, but callingclear()is the portable habit. - Closing. The destructor closes the file and flushes. Call
close()explicitly if you need to check that the final flush succeeded or reopen the same object. - Paths. The
std::filesystem::pathconstructor (C++17) handles non-ASCII names on Windows correctly; plain narrow strings may not. - Binary versus text. On Windows, text mode translates
\r\nto\n. Usestd::ios::binaryfor non-text data and when positions must match byte offsets. - Buffering. Writes sit in a buffer until flushed.
std::endlandflush()force a write; do not use them per line in a large output loop. - Not thread safe. Do not share one file stream between threads without your own locking.