#include <cstdio>
#include <cstring>
#include <string>
using namespace std;
#define SPLIT_SIZE 1048576
#define BUFFER_SIZE 1000
int main(int argc, char const *argv[])
{
printf("rcpkg - resource packager for C/C++(GNU), created by DL.\n");
// check commands
if (argc < 4)
{
printf("Usage: rcpkg input_file_name output_library_name output_directory.\n");
return 0;
}
// check gcc
// FILE* gcc = popen("ruby -v", "r");
FILE* gcc = popen("python --version", "r");
if (!gcc)
{
printf("Cannot execute command.\n");
return 0;
}
char buffer[BUFFER_SIZE];
string res = "";
while(memset(buffer, 0, BUFFER_SIZE - 1), fgets(buffer, BUFFER_SIZE - 1, gcc) != 0)
res += buffer;
printf("========\n%s\n========\n", res.c_str());
pclose(gcc);
// open file
FILE* input = fopen(argv[1], "rb");
if (!input)
{
printf("Cannot open file %s.\n", argv[1]);
return 0;
}
fseek(input, 0, SEEK_END);
auto fs = ftell(input);
fseek(input, 0, SEEK_SET);
printf(">\tSize of file %s is %ld.\n", argv[1], fs);
fclose(input);
return 0;
}
用popen执行"python --version"这个命令,结果用fgets读取不到结果,然而把命令改为"ruby -v"就一切正常,这是为什么啊?
因为 popen() 只能捕获 stdout(标准输出), 忽略了 stderr.
而 python2.7 恰好往 stderr 输出版本信息, 见
https://github.com/python/cpy...
要从 popen() 中捕获 stderr, 可以使用 shell 的重定向功能, 将 stderr 改向 stdout, 如
注
python3.7 的版本信息写往 stdout, 与 python2.7 不同.