2016-09-26 58 views
0

我正在研究一個C程序,該程序是ls命令的修改版本。我已經完成了大部分程序,但我陷入了一個特定的部分。我試圖將最後一個argc參數傳遞給main之外的函數(在另一個文件中更準確)。我嘗試實施如下解決方案:如何將main的argv []值傳遞給外部函數

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; 
} 

這種分配的差不多要點是讓一個通配符filepattern像* foo.c的。搜索目錄和子目錄,並返回結果(文件大小和文件名)以及其他未提及的內容。這是我被卡住的部分,並阻止我前進。

功能listFunc獲取調用由下列函數內部主:ftw(".", listFunc, 1);

我可以張貼的實際分配和所有的到目前爲止我的代碼放在這裏,但將被視爲作弊,不會吧......這麼我想避免這種情況。

+0

filePattern參數是最後一個參數,這就是爲什麼我使用numArguments -1作爲我的索引。 – MazzY

+1

numArguments是一個指針,我認爲'filePattern [numArguments - 1]'是錯誤的。也許'filePattern [* numArguments - 1]'? – Alexi

+0

'argv'是你傳遞給正在執行的二進制文件的任何內容。如果你想OT傳遞給你的'ls'用戶鍵入的內容,然後從內'main'使用'fgets'像這樣: '與fgets(lineBuffer,MAX_LINE_SIZE,標準輸入);'然後通過'lineBuffer'到任何功能,您想。 – ThunderWiring

回答

0

這很難理解。

添加所需參數的功能,並從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是從0開始的像所有的C數組。

我不知道我遵循什麼listFunc()是應該做的,但是這是如何從一個函數傳遞到另一個值。

+0

啊是的抱歉,我沒有更具體/清楚。我一直在做這個工作大約12個小時,而我的大腦幾乎沒有做出全面的句子或邏輯意義。無論如何。爲了說明我在編譯時遇到的錯誤(在進行任何調整之前): listFunc.c:在函數'listFunc'中: listFunc.c:28:20:error:'filePattern'undeclared(first use在此功能) listFunc.c:28:20:注:28:32:錯誤:每個未聲明的標識符是爲它出現在 listFunc.c每個功能只報告一次「numArguments」未聲明(在一次使用此功能) – MazzY

+0

問題是,我在下面的代碼中使用這個函數:'ftw(「。」,listFunc,1);'。正如你所看到的,ftw()調用不會直接從我的listFunc函數中使用任何參數,所以我不知道是否可以向函數添加更多參數 – MazzY

相關問題