從ANSI C編程K & R第69頁,有一個函數的例子,它作爲Unix程序grep的特殊版本。通過K&R getline進行ANSI C編程:--lim> 0或lim - > 0?
的代碼是:
#include <stdio.h>
#define MAXLINE 1000 //max input length
int getline(char line[], int max);
int Strindex(char source[], char searchfor[]);
char pattern[] = "ould";
int main()
{
char line[MAXLINE];
int found =0;
while (getline(line,MAXLINE) > 0)
if (Strindex(line, pattern)>=0){
printf("%s", line);
found ++;
}
return found;
} // end of main function
int getline (char s[], int lim)
{
int c, i;
i = 0;
while (--lim > 0 && (c=getchar()) != EOF && c!= '\n')
s[i++] = c;
if (c == '\n')
s[i++] = c;
s[i] = '\0';
return i;
}
int Strindex (char s[], char t[])
{
int i,j,k;
for (i =0; s[i] != '\0'; i++)
for (i =i, k=0; t[k] != '\0' && s[j] == t[k]; j++, k++);
if (k > 0 && t[k] == '\0')
return i;
}
return -1;
} // end of strindex
是不是一個錯誤:--lim > 0
?如果MAXLINE
在我的情況將是1
,我會在while 0>0
開始 - 錯誤,我不會得到任何字符串?
你從哪裏得到'MAXLINE'會是1的想法? – Nit
有這個代碼塊:if(c =='\ n') s [i ++] = c;如果'lim'的測試改變了,它將超出輸入緩衝區。 – user3629249
而且什麼都不讀的行爲是正確的,因爲一個1字符的緩衝區只能保存字符串的空終止符而不是任何數據。請注意,此練習已被POSIX標準捕獲(超越);現在有一個標準函數['getline()'](http://pubs.opengroup.org/onlinepubs/9699919799/functions/getline.html),它具有與這個'getline()'完全不同的接口。 –