在C中没有成功使用popen()? [英] unsuccessful use of popen() in C?
问题描述
我可以运行以下命令
xwd -root | xwdtopnm | pnmtojpeg > screen.jpg
在Linux下的终端中,它将产生我当前屏幕的屏幕截图.
in a terminal under linux and it will produce a screenshot of my current screen.
我尝试对代码执行以下操作:
I try to do the following with the code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fpipe;
char *command="xwd -root | xwdtopnm | pnmtojpeg";
char line[256];
if ( !(fpipe = (FILE*)popen(command,"r")) )
{ // If fpipe is NULL
perror("Problems with pipe");
exit(1);
}
while ( fgets( line, sizeof line, fpipe))
{
//printf("%s", line);
puts(line);
}
pclose(fpipe);
}
然后我编译并运行程序./popen > screen.jpg
,但生成的文件screen.jpg无法识别.如何做到这一点,以便我可以正确地浏览程序?
then I compile and run the program ./popen > screen.jpg
but the resulting file screen.jpg is unrecongizable. How can I do this so that I can pipe through my program correctly?
推荐答案
您不应使用fgets
和puts
处理二进制数据. fgets
将在看到换行符时停止.更糟糕的是,puts
将输出额外的换行符,并且每当遇到\ 0时它也会停止.改用fread
和fwrite
.
You shouldn't use fgets
and puts
for dealing with binary data. fgets
will stop whenever it sees a newline. Worse, puts
will output extra newlines and it will also stop whenever it runs into a \0. Use fread
and fwrite
instead.
这篇关于在C中没有成功使用popen()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!