Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //v2.0: размер слова не ограничен
- #include <stdio.h>
- #include <string.h>
- #include <stdlib.h>
- #define HASHSIZE 101
- static struct nlist *hashtab[HASHSIZE];
- unsigned hash(char *s);
- struct nlist *lookup(char *s);
- struct nlist *install(char *name);
- void man(int);
- char* eatword (FILE*, FILE*);
- struct nlist {
- struct nlist *next;
- char *name;
- unsigned int qty;
- };
- int main(int argc, char * argv[]){
- if (argc != 2) man(2);
- FILE *fp, *tmpFile;
- tmpFile = tmpfile();
- if ((fp = fopen(argv[1], "r")) == NULL) man(3);
- char *temp;
- int wordNumber = 0, i = 0;
- struct nlist *np, *next, *current;
- while(1){
- if ((temp = eatword(fp, tmpFile)) == NULL) break;
- if (!(np = lookup(temp))) {install(temp); wordNumber++;}
- i++; }
- i = 0;
- printf("\nTotal %d words. Here is the list.\n\n", wordNumber);
- printf("Word Repeats\n");
- while (i <= HASHSIZE) {
- if (hashtab[i] != NULL) {
- current = hashtab[i];
- while (1) {
- if (strcmp(current->name, "\n") != 0)
- printf("%-30s%20d\n", current->name, current->qty);
- if ((current = current->next) == NULL) break; }
- }
- i++; }
- fclose(fp);
- }
- char* eatword(FILE* file, FILE* tmpFile) {
- char c, *word;
- int i = 0, nCount = 0;
- fpos_t pos;
- fgetpos(tmpFile, &pos);
- while ((c = fgetc(file)) == '\n') c = fgetc(file);
- while (((c >= '0') && (c <= '9')) ||
- ((c >= 'A') && (c <= 'Z')) ||
- ((c >= 'a') && (c <= 'z'))) {
- fputc(c, tmpFile);
- c = fgetc(file);
- i++; }
- if (c == EOF) return NULL;
- fputc('\0', tmpFile);
- fsetpos(tmpFile, &pos);
- word = malloc(i+1);
- fgets(word, i+1, tmpFile);
- fsetpos(tmpFile, &pos);
- return word;
- }
- struct nlist *lookup(char *s){
- struct nlist *np;
- for (np = hashtab[hash(s)]; np != NULL; np = np->next)
- if (strcmp(s, np->name) == 0) {
- (np->qty)++;
- return np; }
- return NULL;
- }
- struct nlist *install(char *name){
- struct nlist *np;
- unsigned hashval;
- np = (struct nlist *) malloc(sizeof(*np));
- if (np == NULL || (np->name = strdup(name)) == NULL) return NULL;
- np->qty = 1;
- hashval = hash(name);
- np->next = hashtab[hashval];
- hashtab[hashval] = np;
- return np;
- }
- unsigned hash(char *s){
- unsigned hashval;
- for (hashval = 0; *s != '\0'; s++)
- hashval = *s + 31 * hashval;
- return hashval % HASHSIZE;
- }
- void man(int var) {
- if (var == 0) printf("Программа предназначена для работы с файлами.\nФайл выбирается при помощи аргумента.\nПример: ./a.out file1.txt\nВызов справки -?.\n");
- if (var == 2) printf("Ошибка аргуметов. Укажите файлы при помощи аргумента. -? для справки.\n");
- if (var == 3) printf("Файл не найден.\n");
- if (var > 0) exit(0);
- }
Advertisement
Add Comment
Please, Sign In to add comment