#include <unistd.h>
#include <dirent.h>
#include <stdio.h>
#include <sys/types.h>
#include <stdlib.h>
void list_items(char * p)
{
DIR * d ;
struct dirent * e ;
d = opendir(p) ;
if (d == 0x0)
exit(EXIT_FAILURE) ;
for (e = readdir(d) ; e != 0x0 ; e = readdir(d)) {
if (e->d_type == DT_DIR /* directory */ ||
e->d_type == DT_REG /* regular file */ ) {
printf("%s\n", e->d_name) ;
}
}
}
int main(int args, char ** argv)
{
if (args != 2)
exit(EXIT_FAILURE) ;
list_items(argv[1]) ;
}
所以这打印出来:
./a.out /usr //the input
hello
bin
我需要放置目录,即/ usr和文件名,以便程序比较目录下的文件名并返回所有路径名 所以我需要一个结果,例如这个例子
./a.out /usr hello
/usr/bin/hello
/usr/exe/hello
/usr/python/hello
必须添加到此代码才能获得此结果?谢谢
答案 0 :(得分:1)
基本上,您需要检查参数计数是否为3(而不是2),将后缀传递给list_items()
函数,并打印目录名称和后缀以及文件名。除了一些其他的挞,这导致:
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
static void list_items(char *dirname, char *suffix)
{
DIR *d;
struct dirent *e;
d = opendir(dirname);
if (d == 0x0)
{
fprintf(stderr, "failed to open directory %s\n", dirname);
exit(EXIT_FAILURE);
}
for (e = readdir(d); e != 0x0; e = readdir(d))
{
if (e->d_type == DT_DIR /* directory */ ||
e->d_type == DT_REG /* regular file */)
{
printf("%s/%s/%s\n", dirname, e->d_name, suffix);
}
}
closedir(d);
}
int main(int argc, char **argv)
{
if (argc != 3)
{
fprintf(stderr, "Usage: %s directory suffix\n", argv[0]);
exit(EXIT_FAILURE);
}
list_items(argv[1], argv[2]);
}
示例输出:
$ ls inc
README.md emalloc.h jlss.h range.h wraphead.h
aoscopy.h filter.h kludge.h reldiff.h
chkstrint.h gcd.h microsleep.h stderr.h
debug.h isqrt.h posixver.h timer.h
$ ./dir61 inc podunk
inc/./podunk
inc/../podunk
inc/kludge.h/podunk
inc/emalloc.h/podunk
inc/range.h/podunk
inc/debug.h/podunk
inc/posixver.h/podunk
inc/microsleep.h/podunk
inc/reldiff.h/podunk
inc/isqrt.h/podunk
inc/README.md/podunk
inc/timer.h/podunk
inc/gcd.h/podunk
inc/stderr.h/podunk
inc/jlss.h/podunk
inc/aoscopy.h/podunk
inc/filter.h/podunk
inc/chkstrint.h/podunk
inc/wraphead.h/podunk
$
如果您不想弄乱.
和..
,则必须在测试中排除它们。