Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Mad Mad Access Patterns
- * CS 241 - Fall 2019
- */
- #include "tree.h"
- #include "utils.h"
- #include <stdio.h>
- #include <stdlib.h>
- #include <sys/mman.h>
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <unistd.h>
- #include <fcntl.h>
- #include <string.h>
- /*
- Look up a few nodes in the tree and print the info they contain.
- This version uses mmap to access the data.
- ./lookup2 <data_file> <word> [<word> ...]
- */
- static uint32_t COUNT = 0;
- float findPrice(long int offset, char* word);
- static char* addr = NULL;
- int main(int argc, char **argv) {
- if (argc < 3) { printArgumentUsage(); exit(1); }
- char* filename = argv[1];
- struct stat sb;
- int fd = open(argv[1], O_RDONLY);
- if (fd == -1) { openFail(filename); exit(2); }
- fstat(fd, &sb);
- off_t offset = 0;
- size_t length = sb.st_size; //is this correct?
- off_t page_offset = offset & ~(sysconf(_SC_PAGE_SIZE) - 1);
- addr = mmap(NULL, length + offset - page_offset, PROT_READ, MAP_PRIVATE, fd, page_offset);
- if (addr == NULL) { mmapFail(filename); exit(1); }
- char buf[5];
- memcpy(buf, addr, 4);
- buf[4] = 0;
- if (strcmp(buf, "BTRE") != 0) { formatFail(filename); exit(2); }
- for (int i = 2; i < argc; i++) {
- float price = findPrice(4, argv[i]);
- if (price == -1.0) {
- printNotFound(argv[i]);
- } else {
- printFound(argv[i], COUNT, price);
- }
- }
- munmap(addr, length + offset - page_offset);
- close(fd);
- return 0;
- }
- float findPrice(long int offset, char* word) {
- char nodebuf[sizeof(BinaryTreeNode)];
- BinaryTreeNode* node = (BinaryTreeNode*)memcpy(nodebuf, addr + offset, sizeof(BinaryTreeNode));
- char wordbuf[1024];
- strcpy(wordbuf, addr + offset + sizeof(BinaryTreeNode));
- // printf("current word is: %s\n", wordbuf);
- if (strcmp(wordbuf, word) == 0) { COUNT = node->count; return node->price; }
- if (node->left_child) {
- char leftbuf[sizeof(BinaryTreeNode)];
- memcpy(leftbuf, addr + node->left_child, sizeof(BinaryTreeNode));
- char leftwordbuf[1024];
- strcpy(leftwordbuf, addr + node->left_child + sizeof(BinaryTreeNode));
- // printf("the left word is: %s\n", leftwordbuf);
- // printf("the size of the left word is: %lu\n", sizeof(leftwordbuf));
- // printf("other word is: %s\n", word);
- // printf("the size fo the other word is: %lu\n", sizeof(word));
- if (strcmp(leftwordbuf, word) <= 0) { return findPrice(node->left_child, word); }
- }
- if (node->right_child) {
- char rightbuf[sizeof(BinaryTreeNode)];
- memcpy(rightbuf, addr + node->right_child, sizeof(BinaryTreeNode));
- char rightwordbuf[1024];
- strcpy(rightwordbuf, addr + node->right_child + sizeof(BinaryTreeNode));
- // printf("the right word is: %s\n", rightwordbuf);
- if (strcmp(rightwordbuf, word) > 0) { return findPrice(node->right_child, word); }
- }
- return -1;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement