我正在研究一個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);
我可以張貼的實際分配和所有的到目前爲止我的代碼放在這裏,但將被視爲作弊,不會吧......這麼我想避免這種情況。
filePattern參數是最後一個參數,這就是爲什麼我使用numArguments -1作爲我的索引。 – MazzY
numArguments是一個指針,我認爲'filePattern [numArguments - 1]'是錯誤的。也許'filePattern [* numArguments - 1]'? – Alexi
'argv'是你傳遞給正在執行的二進制文件的任何內容。如果你想OT傳遞給你的'ls'用戶鍵入的內容,然後從內'main'使用'fgets'像這樣: '與fgets(lineBuffer,MAX_LINE_SIZE,標準輸入);'然後通過'lineBuffer'到任何功能,您想。 – ThunderWiring