我有以下代码正在运行,但在每一行中定义一个变量有点烦人:
char *argv[100];
int argc = 0;
argv[0] = "test";
argc = 1;
char verbose[4], source[20], target[20];
int linenum=0;
while(fgets(line, 256, file) != NULL)
{
char arg[20], value[20];
if(line[0] == '#' || strlen(line) < 6) continue;
linenum++;
if(sscanf(line, "%[^=]=%s", arg, value) != 2)
{
fprintf(stderr,"Syntax error: %s\n",line);
continue;
}
if (value && strcmp(arg,"verbose")==0) {
strncpy(verbose,value,sizeof(verbose) - 1);
argv[argc++] = "-v";
argv[argc++] = verbose;
//argv[argc++] = value; //not working, shows 0
}
if (value && strcmp(arg,"source")==0) {
strncpy(source,value,sizeof(source) - 1);
argv[argc++] = "-s";
argv[argc++] = source;
}
if (value && strcmp(arg,"target")==0) {
strncpy(target,value,sizeof(target) - 1);
argv[argc++] = "-t";
argv[argc++] = target;
}
//and so on
|
|
|
|
}
如何从循环内部将“值”复制到单个char?我的意思是避免使用strncpy()
。
答案 0 :(得分:1)
你可以使用这样的表:
int source_checker(char *value) { /* .... */; return 0; }
int verbose_checker(char *value) { /* .... */; return 0; }
int target_checker(char *value) { /* .... */; return 0; }
typedef int (*checker_function)(char *);
const char *label_table[] = { "source", "verbose", "target", 0 };
checker_function checker_table[] = { source_checker, verbose_checker,
target_checker, 0 };
typedef enum { tk_source, tk_verbose, tk_target, tk_END } token;
while(fgets(line, 256, file) != NULL)
{
// ...
for (size_t i = tk_source; i < tk_END; i++) {
if (value && strcmp(arg, label_table[i]) == 0) {
if (checker_table[i](value)) {
break;
}
}
}
答案 1 :(得分:0)
您可以为每个if条件使用循环,并将不同的值存储在预先填充的数组中。
答案 2 :(得分:-1)
如果您尝试保存几行代码,则可以执行此操作
#include <string.h>
....
char* tempstrings[100];
int temps=0;
..
if (value && strcmp(arg,"verbose")==0) {
argv[argc++] = "-v";
argv[argc++] = tempstrings[temps++] = strdup(value);
}
...
// at the end of the program, clean up all the temporary strings
for(int i=0;i<temps;i++) free(tempstrings[i];