《The C Programming Language (2nd Ed.)》第 4 章練習:編寫程式讀取標準輸入,列印所有包含指定模式的行。
argc == 2,模式字串在 argv[1]。getline() 讀取每一行。strstr() 判斷模式是否出現於行中。#include
#include
#define MAXLINE 1000
int getline(char *line, int max);
int main(int argc, char *argv[]) {
char line[MAXLINE];
int found = 0;
if (argc != 2) {
fprintf(stderr, "Usage: %s pattern\n", argv[0]);
return 1;
}
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, i;
for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; i++)
s[i] = c;
if (c == '\n') s[i++] = c;
s[i] = '\0';
return i;
}
| 函數 | 功能 | 回傳值 |
|---|---|---|
getline | 從 stdin 讀取一行至緩衝區 | 讀取字元數,EOF 為 0 |
strstr | 尋找子字串首次出現位置 | 指標或 NULL |
$ gcc find.c -o find
$ echo -e "hello world\npattern match\nno match" | ./find pattern
pattern match
argv[1..n])。-n 顯示行號、-i 忽略大小寫。regex.h 支援正則表達式。mmap 或逐塊讀取避免記憶體壓力。