#include
#include
#define MAXLINE 1000
#define getline _getline
int getline(char *line, int max);
main(int argc, char *argv[])
{
char line[MAXLINE];
int found = 0;
if (argc != 2)
printf("Usage:\n");
else
while (getline(line,MAXLINE)>0)
if (strstr(line,argv[1])!=NULL){
printf("%s",line);
found++;
}
return found;
}
int getline(char *s, int lim)
{
int c;
char *t = s;
while (--lim > 0 && (c = getchar()) != EOF && c != '\n')
*s++ = c;
if (c == '\n')
*s++ = c;
*s = '\0';
return s - t;
}
我理解不了这个程序中这一段
if (strstr(line,argv[1])!=NULL){
printf("%s",line);
strstr返回一个指针,这个指针指向line里面匹配到的内容
那么为什么打印line会打印出这个匹配的内容呢?
http://download.csdn.net/detail/s1230011/4225504
你是在linux系统运行的吧?
我在windows的dos环境下没反应。就输出了一个Usage:
你的getline函数先对line数组执行了操作,
strstr()只是用来判断有没有找到内容的,如果找到了strstr()返回一个地址,然后printf就打印出line中的内容
int getline(char *s, int lim)
{
int c;
char *t = s;
while (--lim > 0 && (c = getchar()) != EOF && c != '\n')
*s++ = c;
if (c == '\n')
*s++ = c;
*s = '\0';
return s - t;
}
因为函数原型extern char *strstr(char *str1, const char *str2);
str1没有const说明在函数中改变了str1指针的位置
所以执行完strstr函数后 line的位置改变了 所以输出的就是找到的那个值
char *strstr(const char *haystack, const char *needle);
The strstr() function finds the first occurrence of the substring nee‐
dle in the string haystack. The terminating null bytes ('\0') are not
compared.