/*
 * This program searches for all instances of a string in a file,
 * printing the line number and line in which it occurs.
 */

#include <stdio.h>
#include <string.h>

/* 
 * This function returns the position of a substring in a string */

int substring_position (char haystack[], char needle[]) {
	int	i, len;

	/* find the length of the thing we're looking for */

	len = strlen (needle);

	/* search at each position in the string */

	for (i=0; haystack[i]; i++) {

		/* if we find it, return the position */

		if (strncmp (&haystack[i], needle, len) == 0) return i;
	}

	/* didn't find it?  return -1. */
	return -1;
}
	
int main (int argc, char *argv[]) {
	FILE	*f;
	char	s[1000];
	int	line_number;

	/* two args: the string and the filename */

	if (argc != 3) {
		fprintf (stderr, "Usage: %s <string> <filename>\n");
		exit (1);
	}
	f = fopen (argv[2], "r");
	if (!f) {

		/* perror gives an error message if something went wrong */

		perror (argv[2]);
		exit (1);
	}

	/* start out at line number 1 */

	line_number = 1;

	/* while not at end of file, get some strings */

	fgets (s, 1000, f);
	while (!feof (f)) {

		/* if we find the substring... */

		if (substring_position (s, argv[1]) != -1) {

			/* print the line number and string */

			printf ("%d: %s", line_number, s);
		}

		/* one more line... */

		fgets (s, 1000, f);
		line_number++;
	}
	fclose (f);
}