strstr関数は、文字列から指定された文字列と一致する部分を検索し、その位置を返します。
#include <string.h>
char *strstr(const char *haystack, const char *needle);
*haystackは検索対象文字列を指定します。
*needleは検索する文字列(検索キー)を指定します。
戻り値として、検索キーと一致する文字列が見つかった場合は、その文字列のポインタを、見つからなかった場合はNULLを返します。
プログラム 例
#include <stdio.h>
#include <string.h>
#define SIZE 1024
int main()
{
FILE *fp;
char path[50]; /* 入力ファイルのパス名 */
char buff[SIZE];
char *start_ptr; /* 検索開始位置 */
char *end_ptr; /* 検索終了位置 */
char *search_ptr; /* 検索結果文字位置 */
char key[11]; /* 検索キー */
int search_cnt; /* 検索結果文字数 */
int return_code = 0;
printf('検索するファイルのパス名を入力してください ==> ');
scanf('%s%*c', path);
if ((fp = fopen(path, 'r')) != NULL) {
printf('検索する文字列を入力してください(10文字以内) ==> ');
scanf('%s', key);
search_cnt = 0;
while(fgets(buff, SIZE, fp) != NULL) {
start_ptr = buff;
end_ptr = buff + strlen(buff);
do {
/* 文字列の検索 */
if((search_ptr = strstr(start_ptr, key)) != NULL) {
++search_cnt;
start_ptr = search_ptr + strlen(key);
}
else {
start_ptr = end_ptr;
}
} while (start_ptr < end_ptr);
}
fclose(fp);
printf('「%s」は%d個ありました\n', key, search_cnt);
}
else {
printf('%sのオープンに失敗しました\n', path);
return_code = 1;
}
return return_code;
}
例の実行結果
$ cat temp_3.txt
Hello World!!.
Hi.
Hello Hello hello.
hello Hello.
Bye.
$
$ ./strstr.exe
検索するファイルのパス名を入力してください ==> temp_3.txt
検索する文字列を入力してください(10文字以内) ==> hello.
「hello.」は1個ありました
$
$ ./strstr.exe
検索するファイルのパス名を入力してください ==> temp_3.txt
検索する文字列を入力してください(10文字以内) ==> Hello
「Hello」は4個ありました
$