讀取文字檔,搜尋使用者輸入的字串,輸出:是否匹配、匹配次數、每次匹配的行號與行內字元位移。
fgets),維護行號計數器。strstr 迴圈查找所有出現位置(處理重疊匹配需手動移動指標)。(行號, 行內偏移)。#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX_LINE 1024
int main() {
FILE *fp = fopen("test.txt", "r");
if (!fp) { perror("open"); return 1; }
char keyword[256];
printf("輸入搜尋字串: ");
scanf("%255s", keyword);
char line[MAX_LINE];
int lineNo = 0, total = 0;
size_t kwLen = strlen(keyword);
while (fgets(line, MAX_LINE, fp)) {
lineNo++;
char *pos = line;
while ((pos = strstr(pos, keyword)) != NULL) {
total++;
int offset = pos - line + 1; // 1-based 字元位置
printf("匹配 #%d: 第 %d 行, 第 %d 字元\n", total, lineNo, offset);
pos += kwLen; // 移至下一個可能位置(非重疊)
// 若需支援重疊匹配,改為 pos += 1;
}
}
if (total == 0) printf("未找到匹配。\n");
else printf("共匹配 %d 次。\n", total);
fclose(fp);
return 0;
}
fgets 保留換行符,strstr 不會跨行匹配,符合逐行邏輯。pos - line 為 0-based,通常顯示為 1-based。mmap 或分塊讀取,避免單行過長超出 MAX_LINE。regex.h (POSIX) 或 PCRE 庫。strcasestr 或轉大小寫後比對。