Store output of system(file) command as a string in C

c, c++

Solution

You can use `popen` like this:

#include <stdio.h>
#include <stdlib.h>

int main( int argc, char *argv[] )
{
  FILE *fp;
  char file_type[40];

  fp = popen("file --mime-type -b filename", "r");
  if (fp == NULL) {
      printf("Failed to run command\n" );
      exit -1;
  }

  while (fgets(file_type, sizeof(file_type), fp) != NULL) {
      printf("%s", file_type);
  }

  pclose(fp);

  return 0;
}

Problem

To get the type of file we can execute the command ``` system("file --mime-type -b filename"); ``` The output displays in to terminal.But could not store the file type using the command ``` char file_type[40] = system("file --mime-type -b filename"); ``` So how to store file type as a string using system(file) function.

Original source

Related problems