c++touchfstreamofstream

C++ ofstream doesn't change mtime


Basically I want to do the same thing as the system call touch (create the file if it doesn't exist, update its modification timestamp if it does).

std::string file = ...;
std::ofstream(file.c_str(), std::ios::app);

This will create the file if it doesn't exist. but it won't change the modification time.

std::string file = ...;
std::ofstream(file.c_str(), std::ios::out);

This will create it if it doesn't exist, it'll update the modification time if it does, but it'll also truncate the file, if it exists.

So how do I touch a file?


Solution

  • Kerrek SB has posted the solution, but unfortunately in a comment rather than an answer (I'd rather accept his answer).

    I've had success with utime(2):

    #include <utime.h>
    ...
    std::string path = "/path/to/my/file";
    bool success = !utime(path.c_str(), 0);
    

    David Schwartz mentioned utimensat for nanosecond precision.