summary refs log blame commit diff stats
path: root/specials/file-search.c
blob: 0644db7ab705488f20ea1158ce59f6721f8ee654 (plain) (tree)






































































                                                                                                           
#include <stdio.h>
#include <stdlib.h>

size_t str_length(char *s)
{
	size_t n = 0;
	while (*s++ != '\0') {
		n++;
	}
	return n;
}

int str_equal(char *a, char *b)
{
	do {
		if (*a++ != *b++) {
			return 0;
		}
	} while (*b != '\0');
	return 1;
}

long find_in_file(FILE *f, char *needle)
{
	size_t nlen = str_length(needle);
	long pos = 0;
	char *str = malloc(nlen + 1);
	while (!feof(f) || !ferror(f)) {
		if (fread(str, 1, nlen, f) != nlen) {
			break;
		}
		str[nlen] = '\0';
		//printf("%ld: %s\n", ftell(f), str);
		if (str_equal(str, needle)) {
			return pos;
		}
		fseek(f, ++pos, SEEK_SET);
	}
	return -1;
}

int main(int argc, char **argv)
{
	FILE *f;
	long pos;
	if (argc < 3) {
		printf("Usage: %s [file] [needle]\n", argv[0]);
		printf("Searches for needle in the contents of file.\n\n");
		return 2;
	}
	if (argv[2][0] == '\0') {
		printf("%s: Invalid needle: needle can not be empty.\n", argv[0]);
		return 3;
	}
	f = fopen(argv[1], "r");
	if (f == NULL) {
		printf("%s: Error: Can not open file `%s` for reading.\n",
			argv[0], argv[1]);
		return 1;
	}
	pos = find_in_file(f, argv[2]);
	if (pos == -1) {
		printf("The string \"%s\" is not found in file `%s`\n",
			argv[2], argv[1]);
	} else {
		printf("The string \"%s\" is found in file `%s` at position %ld\n", argv[2], argv[1], pos);
	}
	fclose(f);
	return 0;
}