目前我正在解析我的C程序中的命令行参数,我想向你学习,如何以最好的方式做到这一点,下面我附上了我的源代码,所以这个程序处理输入看起来像
WAE0500 /f1.txt / d; comment1 comment2
结果将是
收到标志后,我想只使用两个条件:WRITE或READ, 所以我想在这个结构的字段之间切换,我知道下面的代码是错误的,但我希望它有助于理解我的目标:
switch(Flags){
case(flags.write):
// do smth
break;
case(flags.write):
// do smth
break;
}
这是我完整的程序
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef enum { false, true } bool;
typedef struct {
bool debug;
bool help;
bool file_used;
bool read;
bool write;
}Flags;
void parse_input(Flags *flag, int argc, char *argv[], char *file_name);
int main(int argc, char *argv[]) {
Flags flag = { 0,0,0,0,0 };
Flags *flag_ptr = &flag;
char file_name[96];
parse_input(&flag, argc, argv, file_name);
return 0;
}
void parse_input(Flags *flag, int argc, char *argv[], char *file_name) {
int i = 1; int j = 0;
char cur_ch;
while (i != argc) {
cur_ch = argv[i][j];
switch (cur_ch) {
case 'W':
flag->write = true;
break;
case'R':
flag->read = true;
break;
case '/':
j++;
cur_ch = argv[i][j];
switch (cur_ch) {
case 'd':
flag->debug = true;
break;
case 'f':
flag->file_used = true;
if (argv[i][j + 1] != ' ')
strcpy(file_name, &argv[i][j + 1]);
break;
case 'h':
flag->help = true;
break;
default:
printf("Bad Argument: %s\n", argv[i]);
}
break;
case ';': // STOP WHILE
i = argc - 1;
break;
default:
printf("Bad Argument: %s\n", argv[i]);
}
i++;
}
}
这样的选项可以是一个临时解决方案,但我想学习如何正确地做到这一点
char command_type = '\0';
if (flag.write)
command_type = 'W';
else if(flag.read)
command_type = 'R';
switch (command_type) {
case 'W':
//do smth
break;
case 'R':
//do smth
break;
}
UPD2:
enum FlagType { Read, Write, File_used, Debug, Help };
struct S {
FlagType type;
union {
// what to write in union?;
};
};
答案 0 :(得分:0)
这种选择可以是一个临时解决方案,但是我想学习如何正确地做
char command_type = '\0'; if (flag.write) command_type = 'W'; else if(flag.read) command_type = 'R'; switch (command_type) { case 'W': //do smth break; case 'R': //do smth break; }
正确或更准确地说,理智的做法是直接这样做,就像n.m.一样。建议:
if (flag.write)
{
//do smth
}
else
if (flag.read)
{
//do smth
}
不必要地使用带有位掩码的switch
之类的东西。