0

I am trying to parse a json file within my program:

#include <jsoncpp/json/value.h>
#include <jsoncpp/json/json.h>
#include <unistd.h>
#include <stdio.h>

int main(){
    std::string plan { get_current_dir_name() };
    plan += "directory/file.json";
    read_json(plan); // A function that reads a json file using jsoncpp
}

Output:

Error: Json File not found!

However when I manually write the entire path:

#include <jsoncpp/json/value.h>
#include <jsoncpp/json/json.h>
#include <unistd.h>
#include <stdio.h>

int main(){
    std::string plan { entire_file_path };
    read_json(plan); // A function that reads a json file using jsoncpp
}

Output:

File found and read!

I thought maybe there is a spelling mistake but when I use std::cout on both of the paths, there is not a single difference. I'm not sure what is causing this issue.

NotALolicon
  • 31
  • 1
  • 7
  • 1
    Did you verify that `get_current_dir_name` returns a directory with a / at the end? Otherwise you might end up as /home/usernamedirectory/file.json. – Botje Sep 09 '21 at 07:44
  • @Botje Yes, I recognized that issue so I decided to add `"/{Remaining_Path}"`, which returns a complete copy of the full path, though it still did not work for some reason. – NotALolicon Sep 09 '21 at 18:34

1 Answers1

0

Using std::filesystem built-in to C++17:

namespace fs = std::filesystem;
fs::path path = fs::current_path() / "directory" / "file.json";
read_json(path.string());
Botje
  • 26,269
  • 3
  • 31
  • 41