memcmp関数は、メモリ領域のデータを指定された長さだけ比較します。

#include <string.h>
int memcmp(const void *s1, const void *s2, size_t n);

*s1および、*s2は比較するデータの、それぞれの先頭アドレスを指定します。
nは比較する長さをバイト単位で指定します。

戻り値として、次の値を返します。

  1. s1がs2より小さい場合は負の値を返します。
  2. s1とs2が等しい場合は0を返します。
  3. s1がs2より大きい場合は正の値を返します。

プログラム 例

#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    key[11];           /* 比較(検索)文字列 */
  int     search_cnt;        /* 検索結果 */
  int     return_code = 0;

  printf('検索するファイルのパス名を入力してください ==> ');
  scanf('%s', path);

  if ((fp = fopen(path, 'r')) != NULL) {
    printf('検索する文字列を入力してください(10文字以内) ==> ');
    scanf('%10s', key);

    search_cnt = 0;
    while(fgets(buff, SIZE, fp) != NULL) {
      start_ptr = buff;
      end_ptr = buff + strlen(buff);
      do {
        /* 文字列の比較 */
        if(memcmp(start_ptr, key, strlen(key)) == 0) {
          ++search_cnt;
          start_ptr += strlen(key);
        }
        else {
          ++start_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.
$ ./memcmp.exe
検索するファイルのパス名を入力してください ==> temp_3.txt
検索する文字列を入力してください(10文字以内) ==> Hello
Helloは4個ありました
$
$ ./memcmp.exe
検索するファイルのパス名を入力してください ==> temp_3.txt
検索する文字列を入力してください(10文字以内) ==> hello
helloは2個ありました
$