【发布时间】:2011-05-16 12:21:58
【问题描述】:
我正在为 uni 使用 c(或多或少是第一次),我需要从字符数组生成 MD5。分配指定这必须通过创建管道并在系统上执行md5 命令来完成。
我已经走到这一步了:
FILE *in;
extern FILE * popen();
char buff[512];
/* popen creates a pipe so we can read the output
* of the program we are invoking */
char command[260] = "md5 ";
strcat(command, (char*) file->name);
if (!(in = popen(command, "r"))) {
printf("ERROR: failed to open pipe\n");
end(EXIT_FAILURE);
}
现在这很好用(对于需要为文件获取 MD5 的任务的另一部分),但我无法锻炼如何将字符串导入其中。
如果我理解正确,我需要这样做:
FILE * file = popen("/bin/cat", "w");
fwrite("hello", 5, file);
pclose(file);
我认为它会执行 cat,并通过 StdIn 将“hello”传递给它。是这样吗?
【问题讨论】:
-
你运行了第二个块代码吗?如果你有,你会意识到 fwrite 需要另一个参数,它是你的字符串元素的大小,所以你可能会尝试 fwrite("hello",sizeof(char),5,file);并发现这确实有效。无论您是应该这样做还是通过调用 pipe() 然后 fork() 一个孩子,关闭管道的末端,并使用 write() 和 sprintf() 发送信息是一个不同的想法.