2013-01-17 11 views
1

안녕하세요 사람들은 텍스트 파일에서 특정 단어를 검색하는 방법을 찾을 수 없었습니다. 그래서 여기에있는 내용이 제가 지금 가지고있는 것입니다. 전체 텍스트 파일을 읽고 인쇄합니다. . 텍스트 파일에서 특정 단어 검색

#include <stdio.h> 

#include <string.h> 

#include <stdlib.h> 

int main (void) 
{ 

static const char filename[] = "chat.log"; 
FILE *file = fopen (filename, "r"); 
if (file != NULL) 
{ 
char line [ 128 ]; /* or other suitable maximum line size */ 
while (fgets (line, sizeof line, file) != NULL) /* read a line */ 
{ 

fputs (line, stdout); /* write the line */ 
} 
fclose (file); 
} 

else 
{ 
perror (filename); /* why didn't the file open? */ 
} 
return 0; 
} 

감사합니다 : D

+0

'fgets (line, sizeof line, file)! = NULL','sizeof (line)' –

답변

4

사용 strstr(line, word)를 어디서나 라인 내부의 단어를 찾을 수 있습니다. strstr이 NULL이 아닌 값을 반환하면 현재 행에 단어가 있음을 의미합니다.

+0

어디서 쓸 수 있습니까? :) – Winkz

+0

@Winkz'if' 문의 테스트 절에서! :) – user4815162342

+0

는 기압 .. 이런 { (않는 strstr (라인, 손상) { fputs (라인, 표준 출력) 경우는/* 쓰기 라인 */ } } 녹슨 메신저 GD 흠, 그래, 그 – Winkz

1

단어의 고정 세트를 찾고, 난 당신이 Aho-Corasick algorithm에서 봐 제안 :

여기 문자열 검색을위한 훌륭한 알고리즘입니다. 그것은 성능 측면에서 정말 좋습니다.

관련 문제