#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFSIZE 3 /* >= 2 */
char *getline(FILE *fp)
{
static char inbuff[BUFFSIZE];
char *outbuff_malloc, *tmpbuff;
char *p, *q;
int fEOL;
if ((outbuff_malloc = malloc(1)) == NULL) {
return NULL;
}
*outbuff_malloc = '\0';
fEOL = 0;
do {
if ((q = fgets(inbuff, BUFFSIZE, fp)) == NULL)
break;
for (p = inbuff; *p != '\0'; p++)
;
if (*(p - 1) == '\n') {
*(p - 1) = '\0';
fEOL = 1;
}
if ((tmpbuff = realloc(outbuff_malloc, strlen(outbuff_malloc) + strlen(inbuff) + 1)) ==NULL) {
free(outbuff_malloc);
return NULL;
}
strcat(tmpbuff, inbuff);
outbuff_malloc = tmpbuff;
} while (!fEOL);
if (q == NULL) {
free(outbuff_malloc);
return NULL;
}
return outbuff_malloc;
}
int main()
{
char *p, *q;
int sp, sq;
int flag = 0;
printf("input string 1: ");
if ((p = getline(stdin)) != NULL) {
printf("input string 2: ");
if ((q = getline(stdin)) != NULL) {
sp = strlen(p);
sq = strlen(q);
if (sp < sq || sp == 0 || sq == 0) {
printf("no matched.\n");
} else {
unsigned int i, j;
for (i = 0; i < sp - sq + 1; i++) {
for (j = 0; j < sq; j++) {
if (p[i + j] != q[j])
break;
}
if (j == strlen(q)) {
printf("matched %d - %d\n", i, i + strlen(q) - 1);
flag = 1;
}
}
if (flag == 0)
printf("no match.\n");
}
}
}
free(p);
free(q);
return 0;
}
/* end */