要获取文件的类型,我们可以执行命令
system("file --mime-type -b filename");
Run Code Online (Sandbox Code Playgroud)
输出显示在终端中。但无法使用该命令存储文件类型
char file_type[40] = system("file --mime-type -b filename");
Run Code Online (Sandbox Code Playgroud)
那么如何使用 system(file) 函数将文件类型存储为字符串。
popen你可以这样使用:
#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;
}
Run Code Online (Sandbox Code Playgroud)