# include # include # include # include # include # include char * usage = "Usage: %s hashfile overflowfile\n"; const int table_length = 19; const int record_length = 31; int hash(char string[], int len) { int i, s; s = i = 0; while((i < len) && (string[i] != '\0')) { s = (s * 10 + string[i]) % table_length; i++; } return (s); } int write_at_pos(int fd, int pos, char buffer[record_length]) { /* returns -1 on error, 0 on success, 1 if pos occupied */ char ch[2]; if(lseek(fd,pos*record_length,SEEK_SET) <0) { perror("lseek"); return -1; } if (read(fd,ch,1) < 1) { perror("read"); return -1; } if (ch[0] != '\0') return 1; if(lseek(fd,-1,SEEK_CUR) <0) { perror("lseek"); return -1; } if (write(fd,buffer,record_length) < record_length) { perror("write"); return -1; } return 0; } int append_of(int fd, char buffer[record_length]) { if (write(fd,buffer,record_length) < record_length) { perror("write"); return -1; } return 0; } int main(int argc, char * argv[]) { int hfd, ofd, i; char name[record_length]; char empty[record_length]; char buffer[record_length]; /*including null-byte */ if (argc != 3) { fprintf(stderr, usage, argv[0]); exit(1); } for(i=0; i< record_length; i++) empty[i]='\0'; printf("File Size: %d\n", table_length * record_length); if( (hfd = open(argv[1], O_RDWR | O_CREAT | O_TRUNC, 0644)) < 0) { perror("open"); exit(2); } if( (ofd = open(argv[2], O_RDWR | O_CREAT | O_TRUNC | O_APPEND, 0644)) < 0) { perror("open"); exit(2); } /* prepare hashfile: */ /* fill with table_length * record_length zeros */ for(i=0; i < table_length; i++) if( write(hfd, empty, record_length) < record_length) { perror("write"); exit(3); } /* read from stdin: */ memcpy(name,empty,record_length); while( fgets(name, record_length,stdin) != NULL) { /* replace \n by \0:*/ for(i=0; (i < record_length) && (name[i] != '\n'); i++) ; if (i < record_length) name[i] = '\0'; printf("Test: %s -> %d\n", name, hash(name, strlen(name))); memcpy(buffer,name,record_length); switch (write_at_pos(hfd,hash(name,strlen(name)),buffer)) { case -1: perror("write_at_pos"); exit(4); case 1 : fprintf(stderr,"Collossion\n"); if (append_of(ofd,buffer) < 0) { fprintf(stderr, "ERROR\n"); exit(8); } break; default: /*success*/ } memcpy(name,empty,record_length); } exit(0); }