#include #include #include #include #include #include int recur_count = 0; int find_word(char* word, char* search_area, int area_length){ recur_count++; if(area_length < 2) { printf("We gave up\n"); return 0; } int middle = area_length / 2; while(search_area[middle] != '\n' && middle >= 0) middle--; middle++; int end_of_middle_word = middle; while(search_area[end_of_middle_word] != '\n') end_of_middle_word++; write(1, search_area + middle, end_of_middle_word - middle); int res = strncmp(word, search_area + middle, end_of_middle_word - middle); if(!res){ printf(" We found the word!\n"); return middle; } else if(res < 0){ printf(" Look earlier\n"); return find_word(word, search_area, middle); } else { printf(" Look later\n"); return find_word(word, search_area + end_of_middle_word, area_length - end_of_middle_word); } } int main(int argc, char ** argv){ if(argc < 2){ printf("Usage: %s word\n", argv[0]); return 1; } int fd = open("/usr/share/dict/american-english", O_RDONLY); /* This wasn't in the in-class demo. We just used 1024*1024 */ struct stat stats; fstat(fd, &stats); printf("File size is %d bytes\n", stats.st_size); /* After this is just like in class, with two exceptions: * 1. I changed 1024*1024 to stats.st_size everywhere it occured * 2. I changed the output format to be more concise */ char *file_data = mmap(0, stats.st_size, PROT_READ, MAP_SHARED, fd, 0); find_word(argv[1], file_data, stats.st_size); printf("Took %d calls\n", recur_count); munmap(file_data, stats.st_size); close(fd); return 0; }