Save system (file) command output as a string in C

To get the file type, we can execute the command

system("file --mime-type -b filename"); 

The output is output to the terminal. But could not save file type with command

 char file_type[40] = system("file --mime-type -b filename"); 

So, how to save the file type as a string using the system (file) function.

+4
source share
3 answers

See the system manual page: it does not return the result of the command (but the error code or the return value of the command).

You want popen . It returns a FILE* , which you can use to read the output of the command (see the popen man page for more details).

+4
source

You can use popen as follows:

 #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; } 
+4
source

Hmmm, the first and easiest way to figure out what you want is to redirect the output to a temporary file and then read it in the 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 contents of the file.

Of course, before trying to read the temporary file, you will have to check the return value of system () .

+2
source

Source: https://habr.com/ru/post/1491817/


All Articles