【发布时间】:2016-09-26 07:33:31
【问题描述】:
我正在开发一个 C 程序,它是 ls 命令的修改版本。我已经完成了大部分程序,但我被困在一个特定的部分。我正在尝试将最后一个 argc 参数传递给 main 之外的函数(更准确地说是在另一个文件中)。我尝试实施如下解决方案:
char ** filePattern;
filePattern = argv;
int * numArguments;
numArguments = &argc;
上面的代码在我的主目录中。然后我在另一个文件中这样做:
//This Function is Passed to ftw by main.
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <ftw.h>
int listFunc (const char *name, const struct stat *status, int type)
{
//importing the argv and argc from main using pointers
//if the call to stat failed, then just return
if (type == FTW_NS)
{
return 0;
}
//Otherwise, if filename matches the filedescriptor entered by user,
//return found files, their size and filename (with directory)
if(type == FTW_F)
{
if(fnmatch(filePattern[numArguments - 1], name,0 )==0)
{
printf("%ld\t%s\n", status->st_size, name);
}
}
else
{
if(fnmatch(filePattern[numArguments - 1], name,0 )==0)
{
printf("%ld\t%s*\n", status->st_size, name);
}
}
return 0;
}
这个任务的主要内容是获得一个通配符文件模式,如 *foo.c。搜索目录和子目录,并返回结果(文件大小和文件名)以及我没有提到的其他内容。这是我被困住并阻碍我前进的部分。
函数 listFunc 被 main 中的以下函数调用:ftw(".", listFunc, 1);
到目前为止,我可以在此处发布实际作业和我的所有代码,但这会被视为作弊,不是吗...所以我想避免这种情况。
【问题讨论】:
-
filePattern 参数是最后一个参数,这就是我使用 numArguments -1 作为索引的原因。
-
numArguments 是一个指针,我认为
filePattern[numArguments - 1]是错误的。也许filePattern[*numArguments - 1]? -
argv是您传递给正在执行的二进制文件的任何内容。如果您不想将用户键入的内容传递给您的ls,则从main中使用fgets,如下所示:fgets(lineBuffer, MAX_LINE_SIZE, stdin);,然后将lineBuffer传递给您想要的任何功能。
标签: c scope global-variables command-line-arguments main