《C程序设计语言》P101可选参数的使用,打印所有与第一个参数指定的模式相匹配的行
#include <stdio.h>
#include <string.h>
#define MAXLINE 1000//每个文本行的最大长度
/*使用可选参数打印所有与第一个字符串匹配的行*/
int getline(char *line, int max);
int main(int argc, char *argv[])
{
int except = 0, number = 0, lineno = 0;
char c, line[MAXLINE];
while(argc-- > 1 && (*++argv)[0] == '-'){//判断可选参数的类型,作标记
while(c = *++argv[0]){//为防止有-xn这种可选参数写一块的情况
switch(c){
case 'x':
except = 1;
break;
case 'n':
number = 1;
break;
default://有其他不能识别的可选参数
printf("can't define the meaning.");
break;
}
}
}
int l = 0;
while((l = getline(line, MAXLINE)) > 0){//文本行不为空
printf("%d\n", l);
lineno++;//行号
if(number)
printf("%d: ", lineno);
if(except == 1){//打印出不含模式的文本行
if(strstr(line, *argv) == NULL){
printf("%s\n", line);
}
else
printf("the line has the word\n");
}
else//打印出含模式的文本行
{
if(strstr(line, *argv) != NULL){
printf("%s", line);
}
else
printf("no match\n");
}
}
return 0;
}
int getline(char *line, int max)
{
char c, *p = line;
while(max-- > 1 && (c = getchar()) != EOF && c != '\n'){
*line = c;
line++;
}
if(c == '\n'){
*line = c;
line++;
}
*line = '\0';
return line - p - 1;
}
课本上的代码:
int getline(char *line, int max);
int main(int argc, char *argv[])
{
char line[MAXLINE];
long lineno = 0;
int c, except = 0, number = 0, found = 0;
while(--argc > 0 && (*++argv)[0] == '-')
while(c = *++argv[0])
switch(c){
case 'x':
except = 1;
break;
case 'n':
number = 1;
break;
default:
printf("find : illegal option %c\n", c);
argc = 0;
found = -1;
break;
}
if(argc != 1) //不理解为什么要这么判断,意义何在
printf("Usage: find -x -n pattern\n");
else
/*【接下来这一块非常简洁】*/
while(getline(line, MAXLINE) > 0){
lineno ++;
if((strstr(line, *argv) != NULL) != except){ //不理解为什么和P100页的使用argv[1] 是一样的效果。
//这句代码的意思是用了逻辑思维比较的方法:strstr(line, *argv) != NULL 不成立 ,即line中不含有 *argv 模式时,strstr()!=NULL 逻辑值为0时,except为1时,if()成立,总体的意思是:line中不含模式字符串时。 个人认为课本上的这条代码语句的逻辑不方便理解,特别适合对C运用很熟练的人使用。
if(number)
printf("%ld: ", lineno);
printf("%s", line);
found++;
}
else
printf("not match\n");
}
return found;
}
int getline(char *line, int max)
{
char c, *p = line;
while(max-- > 1 && (c = getchar()) != EOF && c != '\n'){
*line++ = c;
}
if(c == '\n')
{
*line++ = c;
}
*line = '\0';
return line - p-1;
}