如何在 C 中将字符串传送到 popen() 命令中?
我在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”传递给它。这是对的吗?
Im working in c (more or less for the first time) for uni, and I need to generate an MD5 from a character array. The assignment specifies that this must be done by creating a pipe and executing the md5
command on the system.
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.
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. Is this right?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
请参阅上面我的评论:
产生一个 md5 和
See my comment above:
produces an md5 sum
尝试一下:
如果您确实想将其写入 md5 的 stdin,然后从 md5 的 stdout 读取,您可能需要寻找 popen2(...) 的实现。但这通常不在 C 库中。
Try this:
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(...). That's not normally in the C library though.
如果您需要将字符串输入
md5
程序,那么您需要知道您的md5
程序使用哪些选项。如果它在命令行上显式地接受一个字符串,则使用它:
如果命令行上未给出文件名,则如果它接受标准输入,则使用:
如果它绝对坚持使用文件名并且您的系统支持
/dev/stdin< /code> 或
/dev/fd/0
,然后使用:md5
,然后删除该文件:If you need to get a string into the
md5
program, then you need to know what options yourmd5
program works with.If it takes a string explicitly on the command line, then use that:
If it takes standard input if no file name is given on the command line, then use:
If it absolutely insists on a file name and your system supports
/dev/stdin
or/dev/fd/0
, then use: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: