diff options
author | smlckz <smlckz@college> | 2021-12-22 14:56:13 +0530 |
---|---|---|
committer | smlckz <smlckz@college> | 2021-12-22 14:56:13 +0530 |
commit | b73983c3717642ca10e7cfe93d97609adc377da9 (patch) | |
tree | a6e9fe4c27e3caa215f8aefa9265fb52f6de4375 /specials/string-search.c | |
download | college-b73983c3717642ca10e7cfe93d97609adc377da9.tar.gz |
backup
Diffstat (limited to 'specials/string-search.c')
-rw-r--r-- | specials/string-search.c | 71 |
1 files changed, 71 insertions, 0 deletions
diff --git a/specials/string-search.c b/specials/string-search.c new file mode 100644 index 0000000..7fa0ec1 --- /dev/null +++ b/specials/string-search.c @@ -0,0 +1,71 @@ +#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 ftell(f); + } + 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; +} + |