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

How do I erase elements from STL containers?

Unfortunately, there isn’t a single uniform interface or pattern for erasing elements from STL containers. But three behaviors emerge: std::vector Pattern To erase elements that fulfill a certain condition from a std::vector, a common technique is the so called erase-remove idiom. If v is an instance of std::vector, and we want to erase elements with … Read more

C++ Add months to chrono::system_clock::time_point

Overview This is a very interesting question with several answers. The “correct” answer is something you must decide for your specific application. With months, you can choose to do either chronological computations or calendrical computations. A chronological computation deals with regular units of time points and time durations, such as hours, minutes and seconds. A … Read more

What is the difference between using a struct with two fields and a pair?

std::pair provides pre-written constructors and comparison operators. This also allows them to be stored in containers like std::map without you needing to write, for example, the copy constructor or strict weak ordering via operator < (such as required by std::map). If you don’t write them you can’t make a mistake (remember how strict weak ordering … Read more

Trouble reading a line using fscanf()

It’s almost always a bad idea to use the fscanf() function as it can leave your file pointer in an unknown location on failure. I prefer to use fgets() to get each line in and then sscanf() that. You can then continue to examine the line read in as you see fit. Something like: #define … Read more