簡體   English   中英

用戶輸入的字符串在c中運行特定的功能

[英]User entered string run a particular function in c

伙計們,所以我正在進行Web服務分配,我讓服務器發出隨機的東西並閱讀uri但現在我想讓服務器運行不同的功能,具體取決於它在uri中讀取的內容。 我知道我們可以用函數指針來做這個,但我不確定如何讀取char *並將其分配給函數指針並讓它調用該函數。 我正在嘗試做的例子: http//pastebin.com/FadCVH0h

我可以使用一個開關聲明我相信,但想知道是否有更好的方法。

對於這樣的事情,您將需要一個將char *字符串映射到函數指針的表。 將函數指針指定給字符串時,程序會出現段錯誤,因為從技術上講,函數指針不是字符串。

注意:以下程序僅用於演示目的。 不涉及邊界檢查,它包含硬編碼值和幻數

現在:

void print1()
{
   printf("here");
}

void print2() 
{
   printf("Hello world");
}
struct Table {
  char ptr[100];
  void (*funcptr)(void)
}table[100] = {
{"here", print1},
{"hw", helloWorld}
};

int main(int argc, char *argv[])
{
   int i = 0;
   for(i = 0; i < 2; i++){
      if(!strcmp(argv[1],table[i].ptr) { table[i].funcptr(); return 0;}
   }
   return 0;
}

我想給你一個非常簡單的例子,我認為,這對於理解C中的函數指針有多好是有用的。(例如,如果你想創建一個shell)

例如,如果您有這樣的結構:

typedef struct s_function_pointer
{
    char*      cmp_string;
    int        (*function)(char* line);
}              t_function_pointer;

然后,您可以設置一個t_function_pointer數組,您將瀏覽它:

int     ls_function(char* line)
{
      // do whatever you want with your ls function to parse line
      return 0;
}

int     echo_function(char* line)
{
      // do whatever you want with your echo function to parse line
      return 0;
}

void    treat_input(t_function_pointer* functions, char* line)
{
       int    counter;
       int    builtin_size;

       builtin_size = 0;
       counter = 0;
       while (functions[counter].cmp_string != NULL)
       {
             builtin_size = strlen(functions[counter].cmp_string);
             if (strncmp(functions[counter].cmp_string, line, builtin_size) == 0)
             {
                   if (functions[counter].function(line + builtin_size) < 0)
                          printf("An error has occured\n");
             }
             counter = counter + 1;
       }
}

int     main(void)
{
     t_function_pointer      functions[] = {{"ls", &ls_function},
                                            {"echo", &echo_function},
                                            {NULL, NULL}};
     // Of course i'm not gonna do the input treatment part, but just guess it was here, and you'd call treat_input with each line you receive.
     treat_input(functions, "ls -laR");
     treat_input(functions, "echo helloworld");
     return 0;
}

希望這可以幫助 !

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM