[英]How Do I Pipe a String Into a popen() Command in C?
Im working in c (more or less for the first time) for uni, and I need to generate an MD5 from a character array. 我在uni(或多或少是第一次)为uni工作,我需要从字符数组生成MD5。 The assignment specifies that this must be done by creating a pipe and executing the
md5
command on the system. 赋值指定必须通过创建管道并在系统上执行
md5
命令来完成此操作。
I've gotten this far: 我到目前为止:
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);
}
Now this works perfectly (for another part of the assignment which needs to get the MD5 for a file) but I cant workout how to pipe a string into it. 现在这完美地工作(对于需要获取文件的MD5的任务的另一部分)但是我不能锻炼如何将字符串输入其中。
If I understand correctly, I need to do something like: 如果我理解正确,我需要做以下事情:
FILE * file = popen("/bin/cat", "w");
fwrite("hello", 5, file);
pclose(file);
Which, I think, would execute cat, and pass "hello" into it through StdIn. 我认为,它会执行cat,并通过StdIn将“hello”传递给它。 Is this right?
这是正确的吗?
If you need to get a string into the md5
program, then you need to know what options your md5
program works with. 如果你需要在
md5
程序中输入一个字符串,那么你需要知道你的md5
程序使用的选项。
If it takes a string explicitly on the command line, then use that: 如果它在命令行上显式地使用了一个字符串,那么使用它:
md5 -s 'string to be hashed'
If it takes standard input if no file name is given on the command line, then use: 如果在命令行中没有给出文件名,则采用标准输入,则使用:
echo 'string to be hashed' | md5
If it absolutely insists on a file name and your system supports /dev/stdin
or /dev/fd/0
, then use: 如果它绝对坚持文件名并且您的系统支持
/dev/stdin
或/dev/fd/0
,那么使用:
echo 'string to be hashed' | md5 /dev/stdin
If none of the above apply, then you will have to create a file on disk, run md5
on it, and then remove the file afterwards: 如果以上都不适用,那么您必须在磁盘上创建一个文件,在其上运行
md5
,然后删除该文件:
echo 'string to be hashed' > file.$$; md5 file.$$; rm -f file.$$
See my comment above: 请参阅上面的评论:
FILE* file = popen("/sbin/md5","w");
fwrite("test", sizeof(char), 4, file);
pclose(file);
produces an md5 sum 产生一个md5总和
Try this: 尝试这个:
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
}
If you really want to write it to md5's stdin, and then read from md5's stdout, you're probably going to want to look around for an implementation of popen2(...). 如果你真的想把它写到md5的stdin,然后从md5的stdout读取,你可能会想要四处寻找popen2(...)的实现。 That's not normally in the C library though.
但这通常不在C库中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.