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

后端 未结 3 1254
你的背包
你的背包 2021-01-19 05:02

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

相关标签:
3条回答
  • 2021-01-19 05:15

    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;
    }
    
    0 讨论(0)
  • 2021-01-19 05:22

    See the man page of system: It does not return the output of the command executed (but an errorcode or the return value of the command).

    What you want is popen. It return a FILE* which you can use to read the output of the command (see popen man page for details).

    0 讨论(0)
  • 2021-01-19 05:22

    Hmmm the first and easiest way that comes to my mind for achieving what you want would be to redirect the output to a temp-file and then read it into a char buffer.

    system("file --mime-type -b filename > tmp.txt");
    

    after that you can use fopen and fscanf or whatever you want to read the content of the file.

    Ofcourse, youl'll have the check the return value of system() before attempting to read the temp-file.

    0 讨论(0)
提交回复
热议问题