用户输入的字符串在c中运行一个特定的函数
问题描述:
伙计们,所以我正在处理Web服务分配和我有服务器dishing出随机的东西,并阅读uri,但现在我想让服务器运行一个不同的功能取决于它在uri中读取的内容。我明白,我们可以用函数指针来做到这一点,但我不确定如何读取char *并将其分配给函数指针并使其调用该函数。 我想要做的例子:http://pastebin.com/FadCVH0h用户输入的字符串在c中运行一个特定的函数
我可以使用switch语句,我相信但是想知道是否有更好的方法。
答
对于这样的事情,你需要一个将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;
然后,您可以设置up一个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;
}
希望这有助于!