Escaping characters in a filename string

Viewed 72

I am trying to calculate the sha256sum of a file, that has a number of "problematic" characters in its name:

#include <iostream>
#include <string>
#include <filesystem>
#include <fstream>

int main(){
   std::string filename = "photo i too in brasil(1).jpg";
   std::string command = "sha256sum " + filename;
   std::cout << command << std::endl;
   std::array<char, 128> buffer;
   std::string result;

   FILE* pipe = popen(command.c_str(), "r");
   if (!pipe)
   {
      std::cerr << "Couldn't start command." << std::endl;
      return 0;
   }
   while (fgets(buffer.data(), 128, pipe) != NULL) {
      result += buffer.data();
   }
   auto returnCode = pclose(pipe);   
}

Which results in:

(base) > $ ./a.out                                                                                                                                                                                                                                                             
sha256sum photo i too in brasil(1).jpg
sh: 1: Syntax error: "(" unexpected

I know I could write a routine, that looks for all problem characters and replaces them with the corresponding escape, but I was wondering if there is a smarter way to do this? Is there already some routine like this in the STL? In python I can tell the shutils, that "bla bla bla" is one argument. Can I do this in c++ as well?

1 Answers

In the end I used regex to add a backslash before every space or bracket. This was also very concise.

Related