1

I have a single string that i need to do a couple of concatenations to. This is my first time dealing with strings in cpp and the methods I need to use seems to be taking a char* and not std::string. this is what i need to do:

String folderpath = "something";
folderpath +="/"+dbName;
mkdir(folderpath);
foo(folderpath + "/" +dbName + ".index");
bar(folderpath + "/" +dbName + ".db");

This is how i've managed to do it in C++ and it looks so bad. Is there a better way?

char* folderPath = getenv("CAVEDB_ROOT_FOLDER");
strcat(folderPath, "/");
strcat(folderPath, dbName);
mkdir(folderPath);
char* indexfile;
char* dbfile;
strcpy(indexfile, folderPath);
strcpy(dbfile, folderPath);
strcat(indexfile, "/");
strcat(indexfile, dbName);
strcat(indexfile, ".index")
strcat(dbfile, "/");
strcat(dbfile, dbName);
strcat(dbfile, ".db");
foo(indexfile);
bar(dbfile);

1 Answers1

3

std::string has a c_str() method for getting a const char* pointer, eg:

std::string folderpath = "something";
folderpath += "/" + dbName;
mkdir(folderpath.c_str());
folderpath += "/" + dbName;
foo((folderpath + ".index").c_str());
bar((folderpath + ".db").c_str());

That being said, in C++17 and later you should use the functions and classes in the <filesystem> library (in earlier versions, you can use boost::filesystem instead), eg:

#include <filesystem>
namespace fs = std::filesystem;

fs::path folderpath = "something";
folderpath /= dbName;
fs::create_directory(folderpath);
folderpath /= dbName;
folderpath += ".index";
foo(folderpath.string().c_str());
folderpath.replace_extension(".db");
bar(folderpath.string().c_str());
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770