4

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.

2
  • return value of system() will be -1 or status of command execution only. Commented Jul 17, 2013 at 8:59
  • 5
    Solution: stackoverflow.com/questions/43116/…. Commented Jul 17, 2013 at 9:02

3 Answers 3

6

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

sizeof(file_type)-1 is bogus; sizeof file_type is good enough. (fgets always results in a nul-terminated string) BTW: file_type is not initialised. Note: you don't need the parens
4

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).

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.