【问题标题】:How to pass an argv[] value from main to an outside function如何将 argv[] 值从 main 传递到外部函数
【发布时间】: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


【解决方案1】:

这很难理解。

将所需的参数添加到函数中,并在调用时从main() 传递。不要使用全局变量!

像这样:

int listFunc (const char *pattern, const char *name, const struct stat *status, int type)
{
  ...
}

然后在main():

listFunc(argv[argc - 1], rest of parameters ...);

它是 argc - 1,因为 argv 和所有 C 数组一样是从 0 开始的。

我不确定我是否遵循 listFunc() 应该做的事情,但这是将值从一个函数传递给另一个函数的方法。

【讨论】:

  • 啊,是的,对不起,我没有更具体/清楚。已经为此工作了大约 12 个小时,我的大脑几乎没有做出全面的句子或逻辑意义。反正。阐明我在编译时遇到的错误(在进行任何调整之前):listFunc.c: In function 'listFunc': listFunc.c:28:20: error: 'filePattern' undeclared (首先在这个函数中使用) listFunc.c:28:20: 注意:每个未声明的标识符对于它出现在 listFunc.c:28:32 中的每个函数只报告一次:错误:'numArguments' 未声明(在此函数中首次使用)
  • 问题是,我在下面的代码中使用了这个函数:ftw(".", listFunc, 1);。如您所见,ftw() 调用不直接使用来自我的 listFunc 函数的任何参数,所以我不知道是否可以向函数添加更多参数
猜你喜欢
  • 2022-08-03
  • 2011-05-02
  • 2011-12-14
  • 1970-01-01
  • 2019-12-13
  • 2017-03-13
  • 2023-03-09
  • 2021-12-22
  • 1970-01-01
相关资源
最近更新 更多