1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
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 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;
}
|