How can I use non-default delimiters when reading a text file with std::fstream?

An istream treats “white space” as delimiters. It uses a locale to tell it what characters are white space. A locale, in turn, includes a ctype facet that classifies character types. Such a facet could look something like this: #include <locale> #include <iostream> #include <algorithm> #include <iterator> #include <vector> #include <sstream> class my_ctype : public … Read more

Why is failbit set when eof is found on read?

The failbit is designed to allow the stream to report that some operation failed to complete successfully. This includes errors such as failing to open the file, trying to read data that doesn’t exist, and trying to read data of the wrong type. The particular case you’re asking about is reprinted here: char buffer[10]; stream.read(buffer, … Read more

How to truncate a file while it is open with fstream

I don’t think you can get “atomic” operation but using the Filesystem Technical Specification that has now been accepted as part of the Standard Library (C++17) you can resize the file like this: #include <fstream> #include <sstream> #include <iostream> #include <experimental/filesystem> // compilers that support the TS // #include <filesystem> // C++17 compilers // for … Read more

Retrieving file descriptor from a std::fstream [duplicate]

You can go the other way: implement your own stream buffer that wraps a file descriptor and then use it with iostream instead of fstream. Using Boost.Iostreams can make the task easier. Non-portable gcc solution is: #include <ext/stdio_filebuf.h> { int fd = …; __gnu_cxx::stdio_filebuf<char> fd_file_buf{fd, std::ios_base::out | std::ios_base::binary}; std::ostream fd_stream{&fd_file_buf}; // Write into fd_stream. // … Read more

std::fstream buffering vs manual buffering (why 10x gain with manual buffering)?

This is basically due to function call overhead and indirection. The ofstream::write() method is inherited from ostream. That function is not inlined in libstdc++, which is the first source of overhead. Then ostream::write() has to call rdbuf()->sputn() to do the actual writing, which is a virtual function call. On top of that, libstdc++ redirects sputn() … Read more