On this page
std::iostream & std::fstream
Prev: std::filesystem::path | Up: io_and_filesystem | Next: Language & RAII
Rel: std::format & std::print, RAII & Destructors
Ref: cppreference — Input/Output Library
Tags: #public #prog #cpp #stdlib #io #tier/standard
Overview
<iostream> (std::cin, std::cout, std::cerr) and <fstream> (std::ifstream, std::ofstream) provide RAII stream-based I/O—file streams automatically flush and close in their destructors.
Notes & Pitfalls
- Use
'\n'instead ofstd::endl:std::endlforces an expensive buffer flush on every line. - Check stream truthiness (
while (std::getline(in, line))) instead ofwhile (!in.eof()).
Example
#include <cassert>
#include <sstream>
#include <string>
int main() {
std::istringstream in("first\nsecond\n");
std::string line;
int count = 0;
while (std::getline(in, line)) ++count;
assert(count == 2);
}
Linked from
Related notes
- tuts/cpp/stdlib/io_and_filesystem/format_and_print Linked here; links to this page; shared tags: #cpp, #io, #prog, #stdlib, #tier
- tuts/cpp/stdlib/io_and_filesystem Linked here; links to this page; shared tags: #cpp, #io, #prog, #stdlib
- tuts/cpp/stdlib/io_and_filesystem/filesystem_path Linked here; links to this page; shared tags: #cpp, #prog, #stdlib, #tier
- tuts/cpp/builtins/raii_and_destructors Linked here; shared tags: #cpp, #prog, #tier
- tuts/cpp/language_and_raii Linked here; shared tags: #cpp, #prog
- tuts/cpp/stdlib/algorithm_and_ranges/find_if shared tags: #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/algorithm_and_ranges/ranges_views shared tags: #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/algorithm_and_ranges/sort shared tags: #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/algorithm_and_ranges/transform shared tags: #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/concurrency/atomic shared tags: #cpp, #prog, #stdlib, #tier