在命令参数中使用无效输入或-help
标志时,会出现段错误。它是Unix expand
实用程序的重新创建,它应该以类似的方式处理错误。使用无效输入时出现Segfault
int main(int argc, char *argv[]){
char help1[]= "-help";
char help2[]= "--help";
int spaces; //number of spaces to replace tabs
if (argc==1){ //if only one argument in stack
//check if asking for help
if ((strcmp(argv[1], help1)==0) || (strcmp(argv[1], help2)==0))
printHelp();
else
printError(); //otherwise, print error message
//right number of tokens are provided, need to validate them
} else if (argc>=2){
spaces= atoi(argv[2]); //assign it to spaces
parse_file(spaces); //open the stream and pass on
}
return 0;
}
我printerror方法:
void printError(){
fprintf(stderr, "\nInvalid Input.\n");
fprintf(stderr, "The proper format is myexpand -[OPTION] [NUMBER OF SPACES]\n");
exit(1);
}
当我尝试输入无效或帮助的标志,我得到一个段错误。为什么会这样,因为我在检查第一面旗子是否有帮助?
有一段时间没有做任何C,但不是索引0索引? strcmp(argv [1] ...应该是strcmp(argv [0]等等)? – Gazler 2011-02-10 20:07:53
不,argv [0]是你的可执行文件的名称 – chris 2011-02-10 20:11:07