Search code examples
c++debianspdlog

spdlog for C++; what(): Failed opening file ~/logs/log.txt for writing: No such file or directory


I am using spdlog to do some simple logging on a c++ program on a beaglebone, debian 10. I set up a rotating logger:

auto logger = spdlog::rotating_logger_mt("runtime_log", "~/logs/log.txt", max_size, max_files);

and this returns the error

terminate called after throwing an instance of spdlog::spdlog_ex'
  what():  Failed opening file ~/logs/log.txt for writing: No such file or directory
Aborted

I have already ensured that the directory exists and have tried chmod -R 776 ~/logs/ so:

drwxrwxrw- 2 user group 4096 Oct 28 09:03 logs
-rwxrwxrw- 1 user group 0 Oct 28 09:03 runtime.log

When given the path logs/log.txt, it works. This puts the logfile in ~/project/build/logs

I have also tried giving the full path /home/user/logs/log.txt. And that works fine.

Why would my program and spdlog not be able to access the directory at the path ~/logs/log.txt?


Solution

  • ~ is special character in Bash shell, shorthand for home directory. The C++ program doesn't know about the ~. Usual way to get home directory would be to use std::getenv function like:

    const char* home_dir = std::getenv("HOME");
    auto log_path = std::string{home_dir} + "/logs/log.txt";
    

    I suggest you also to make use of <filesystem> header as it has functions to check the existence of files and directories.