我试图在C程序中使用命令,现在Im使用dirent.h获取文件夹中的所有文件,现在,我想获得所有这些文件的md5,我正在这样做:
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include <syslog.h>
#include <string.h>
#include <dirent.h>
int main(void){
char *word = ".gz";
int i=0;
char *word2 = ".";
char *word3 = "..";
unsigned int md5;
DIR *d;
struct dirent *dir;
d = opendir(".");
if (d) {
while ((dir = readdir(d)) != NULL)
{
if((strstr(dir->d_name, word) == NULL) && (strcmp(dir->d_name, word2) != 0) && (strcmp(dir->d_name, word3)!= 0)) {
md5 = system("md5sum dir->d_name");
printf("The md5 of %s is %d\n", dir->d_name, md5);
}
}
}
return(0);
}但是当我运行它时,它说,例如:
md5sum: dir-: No such file or directory
The md5 of ej1_signal.c is 256
md5sum: dir-: No such file or directory
The md5 of pipeL.c is 256你能解释一下为什么会这样吗?谢谢!
发布于 2014-12-27 16:13:13
system函数不会返回您所想的内容。system用于启动命令,当该命令完成时,它(通常)使用退出代码退出。这就是你所捕捉到的价值。
您需要的是命令的输出,而不是它的返回值。因此,您需要的是popen,它允许您启动一些外部命令,并通过管道对其进行读写。例如,请参见http://pubs.opengroup.org/onlinepubs/009695399/functions/popen.html。
发布于 2014-12-27 16:13:12
system不返回命令的输出。要获得命令的输出,您需要创建一个进程,并将标准输出流绑定到一个文件描述符上,您可以在另一个进程中读取数据。关于如何这样做的示例,您可以参考pipe手册页(第2节)。
另一种选择是使用提供MD5实现的库(例如。OpenSSL)。EVP_DigestInit的手册页(第3节)提供了一个示例。
另一个问题是,您的代码试图计算d->d_name的摘要,而不是d->d_name中名称的文件。您可以使用sprintf或strncat与适当大小的缓冲区(即。静态字符串部分md5sum的长度加上文件名的最大大小(通常为256个字节,在库实现和文件系统之间可能有所不同)加上另一个字节以安全终止字符串(因为一些实现可能在d->d_name中报告一个未终止的字符串)。请注意,如果您使用库进行摘要计算,则不适用于此,因为库使用文件名或需要将文件内容传递给库函数(例如。EVP_DigestUpdate)。
发布于 2014-12-27 16:21:28
第一个问题是启动一个执行"md5sum dir->d_name"的新shell进程,这意味着它在名为dir->d_name的“文件”上执行一个md5,而不是使用从readdir获得的值。
因此,您可以添加一个temp变量,并在运行系统之前在其中准备命令。
limits.h适用于Linux,必要时对其进行调整以获得路径的最大长度。
...
#include <linux/limits.h>
char temp[PATH_MAX];然后,代替
md5 = system("md5sum dir->d_name");添加
strcpy(temp, "md5sum ");
strcat(temp, dir->d_name);
system(temp);至于另一个问题(系统不会返回md5字符串),这将在目录中显示文件的md5。你可以移除指纹..。
https://stackoverflow.com/questions/27668982
复制相似问题