我目前正在使用一个代码示例,最初设计用于获取参数,然后在当前目录中搜索该参数,我试图通过替换"."来搜索另一个目录(/ dev/shm to exact). " 使用"/ dev/shm"但是当我搜索某些内容时代码没有任何内容*(请注意通配符).通配符搜索在当前目录中正常工作,所以我不认为这是外卡是问题,如果有人可以帮助我,虽然我真的很感激,谢谢!
#include <dirent.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
static void lookup(const char *arg)
{
DIR *dirp;
struct dirent *dp;
if ((dirp = opendir(".")) == NULL) {
perror("couldn't open '.'");
return;
}
do {
errno = 0;
if ((dp = readdir(dirp)) != NULL) {
if (strcmp(dp->d_name, arg) != 0)
continue;
(void) printf("found %s\n", arg);
(void) closedir(dirp);
return;
}
} while (dp != NULL);
if (errno != 0)
perror("error reading directory");
else
(void) printf("failed to find %s\n", arg);
(void) closedir(dirp);
return;
}
int main(int argc, char *argv[])
{
int i;
for (i = 1; i < argc; i++)
lookup(argv[i]);
return (0);
}
Run Code Online (Sandbox Code Playgroud)
opendir不处理通配符.它需要一个真正的目录路径.你说的时候我不确定你的意思
通配符搜索在当前目录中有效
如果你的意思是它在你的shell中工作,那就是预期的.shell将首先展开通配符,然后执行您键入的命令.
那么如何解决这个问题?glob在调用之前使用自己扩展通配符opendir.
编辑:对不起,我以为你试图匹配目录名中的通配符.看起来您希望使用通配符匹配目录内容.在这种情况下,只需更换
if (strcmp(dp->d_name, arg) != 0)
Run Code Online (Sandbox Code Playgroud)
同
if (fnmatch(arg, dp->d_name, 0) != 0)
Run Code Online (Sandbox Code Playgroud)
你也可以用glob它.它实际上会取代opendir对循环的调用.以下是使用示例glob:
#include <glob.h>
#include <stdio.h>
static void lookup(const char *root, const char *arg)
{
size_t n;
glob_t res;
char **p;
chdir(root);
glob(arg, 0, 0, &res);
n = res.gl_pathc;
if (n < 1) {
printf("failed to find %s\n", arg);
} else {
for (p = res.gl_pathv; n; p++, n--) {
printf("found %s\n", *p);
}
}
globfree(&res);
}
int main(int argc, char *argv[])
{
int i;
for (i = 2; i < argc; i++)
lookup(argv[1], argv[i]);
return (0);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10502 次 |
| 最近记录: |