我在uni(或多或少是第一次)为uni工作,我需要从字符数组生成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”传递给它。这是对的吗?
答案 0 :(得分:2)
如果您需要在md5
计划中添加字符串,那么您需要了解md5
计划的工作方式。
如果在命令行中显式使用了字符串,则使用:
md5 -s 'string to be hashed'
如果在命令行中没有给出文件名,则采用标准输入,然后使用:
echo 'string to be hashed' | md5
如果它绝对坚持文件名,并且您的系统支持/dev/stdin
或/dev/fd/0
,请使用:
echo 'string to be hashed' | md5 /dev/stdin
如果以上都不适用,那么您必须在磁盘上创建一个文件,在其上运行md5
,然后删除该文件:
echo 'string to be hashed' > file.$$; md5 file.$$; rm -f file.$$
答案 1 :(得分:1)
请参阅上面的评论:
FILE* file = popen("/sbin/md5","w");
fwrite("test", sizeof(char), 4, file);
pclose(file);
产生md5总和
答案 2 :(得分:0)
试试这个:
static char command[256];
snprintf(command, 256, "md5 -qs '%s'", "your string goes here");
FILE* md5 = popen(md5, "r");
static char result[256];
if (fgets(result, 256, md5)) {
// got it
}
如果你真的想把它写到md5的stdin,然后从md5的stdout读取,你可能会想要四处寻找popen2(...)的实现。但这通常不在C库中。