0

我在运行编译的 C 代码时尝试传递多个参数

代码是这样的

void main(char argc,char *argv[]){

    printf("%s",argv[1])    //filename
    FILE *file = fopen(argv[1], "r")

    printf("%s",argv[2])    //function to be called
    char* func_name = argv[2];

    printf("%s",argv[3])    //how many times the function is called
    int repeat = argv[3];

    for(int i=0;i<repeat;i++){
        func_name(file) //calls some function and passes the file to it 
    }

}

我会这样编译

gcc cprog.c -o cprog

像这样跑——

./cprog textfile.txt function1 4 

我该怎么做呢 ?任何帮助,将不胜感激 !

4

3 回答 3

1

首先:

  1. 您缺少一些分号,因此您的代码甚至无法编译。
  2. argv[]strings,所以如果你想这样使用它们,你必须将它们转换为整数。
  3. C 不将函数名称存储在二进制文件中,因此您必须创建某种调用表。

下面找到一个工作示例。我创建了一个struct将名称映射到函数的函数,实现该函数并查找它。它非常有问题(没有进行输入验证),但为您提供了有关如何实现此功能的概念证明。

#include <stdlib.h>
#include <stdio.h>

struct fcn_entry {
  char *name;
  void (*fcn)(char *);
};

void fcn1(char *fn) {
   printf("fcn1: %s\n", fn);
}

void fcn2(char *fn) {
   printf("fcn2: %s\n", fn);
}

void main(char argc,char *argv[]){
    // name-to-function table
    struct fcn_entry entries[] = {
        { "fcn1", fcn1 },
        { "fcn2", fcn2 },
        { NULL, NULL }
    };
    void (*fcn_to_call)(char *);
    int i = 0;

    printf("%s",argv[1]);    //filename

    printf("%s",argv[2]);    //function to be called    
    char* func_name = argv[2];
    i = 0;
    while(entries[i].name != NULL) {
        if (strcmp(entries[i].name, func_name) == 0) {
           fcn_to_call = entries[i].fcn;
           break;
        } else {
           fcn_to_call = NULL;
        }
        i++;
    }


    printf("%s",argv[3]);    //how many times the function is called
    int repeat = atoi(argv[3]);

    for(i=0;i<repeat;i++){
        fcn_to_call(argv[1]);
    }
}
于 2013-08-13T11:43:38.947 回答
1

为了能够调用字符串形式的函数,您必须知道哪个名称与哪个函数配对。

如果所有函数都采用相同的参数,您可以拥有一个带有名称和函数指针的结构数组,然后将名称与表中的正确条目匹配。

否则,如果参数不同,则必须进行一系列strcmp调用才能调用正确的函数。

于 2013-08-13T11:28:22.080 回答
1

这里有很多错误。

int repeat = argv[3]; //You must convert char* to int before assignment.
func_name(file)       //func_name is a char* not a function. C does not support reflection so there is no way to call function like this.
于 2013-08-13T11:38:31.587 回答