Search code examples
c++popen

C++ popen() parameter


I have a question about using popen() in C++.

The code below works fine and you can put "ls" directly in as the first parameter of popen().

FILE *fp;
char returnData[64];

fp = popen("ls","r");
if (fp == NULL){
   }
   else{
while (fgets(returnData, 64, fp) != NULL){
      fprintf( stdout, "%s", returnData  );
            }
        }

However, this code does not work. Why can I not use the string called command as a parameter? It is necessary to append .c_str().

FILE *fp;
char returnData[64];
string command = "ls";

fp = popen(command,"r"); // fp = popen(command.c_str(),"r");
if (fp == NULL){
   }
   else{
while (fgets(returnData, 64, fp) != NULL){
      fprintf( stdout, "%s", returnData  );
            }
        }

Could somebody explain the difference?

Thank you


Solution

  • tl;dr You are mixing C and C++.

    popen() is a C-API function, therefore strings are C-strings (NUL terminated array of chars).

    You are using std::string, a C++ object, and there is no automatic conversion from std::string to const char *, so you have to provide that yourself, using the c_str() method.