Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "hierarchy.h"
- #include <stdio.h>
- #include <string.h>
- #include <stdlib.h>
- #define MAXL1 20
- #define MAXL2 50
- struct hier
- {
- char *name;
- char **songs;
- int num;
- };
- int charChecker(char *p)
- {
- if(p==NULL)
- {
- printf("errore di allocazione caratteri");
- exit(9);
- }
- return 0;
- }
- hierarchy newAuthor(char *nm)
- {
- hierarchy new=malloc(sizeof(hierarchy));
- new->name=malloc(strlen(nm)+1);
- new->songs=malloc(sizeof(char*));
- strcpy(new->name, nm);
- new->num=0;
- }
- void addSong(hierarchy p, char *nm)
- {
- p->songs=realloc(p->songs, sizeof(char*)*(numEl(p)+1));
- if(!p->songs) exit(9);
- p->songs[numEl(p)]=malloc(strlen(nm)+1);
- strcpy(p->songs[numEl(p)], nm);
- p->num++;
- }
- char *authorName(hierarchy p)
- {
- return p->name;
- }
- char **songNames(hierarchy p)
- {
- return p->songs;
- }
- int numEl(hierarchy p)
- {
- return p->num;
- }
- void printHierarchy(hierarchy p)
- {
- for(int i=0; i<numEl(p); i++)
- printf("%s\t %s\n", authorName(p), songNames(p)[i]);
- }
- void printAllHierarchy(hierarchy *p, int n)
- {
- for(int i=0; i<n; i++)
- printHierarchy(p[i]);
- }
- //funzione di servizio
- int searchAuthor(hierarchy* res, char *author, int numAuthors)
- {
- for(int i=0; i<numAuthors ; i++)
- if(strcmp(authorName(res[i]), author)==0)
- return 1; //trovato
- return 0; //non trovato
- }
- //funzione di servizio
- int findAuthorNum(hierarchy *res, char *author, int numAuthors)
- {
- int i=0;
- for(; i<numAuthors ; i++)
- if(strcmp(authorName(res[i]), author)==0)
- return i;
- }
- void newAuthor2(hierarchy *p, int i, char *name)
- {
- p[i]=malloc(sizeof(hierarchy));
- if(!p[i]) exit (9);
- p[i]->name=malloc(strlen(name)+1);
- charChecker(p[i]->name);
- strcpy(p[i]->name, name);
- p[i]->num=0;
- }
- hierarchy *extract(FILE *p)
- {
- int numAuthors=0, MAX=5;
- char *author, *song;
- hierarchy *result=malloc(sizeof(hierarchy)*MAX);
- while(!feof(p))
- {
- if(numAuthors>=MAX)
- {
- MAX+=1;
- result=realloc(result, sizeof(hierarchy)*MAX);
- }
- author=malloc(sizeof(char)*MAXL1);
- song=malloc(sizeof(char)*MAXL2);
- charChecker(author);
- charChecker(song);
- fscanf(p, "%s\t %s", author, song);
- author=realloc(author, strlen(author)+1);
- song=realloc(song, strlen(song)+1);
- charChecker(author);
- charChecker(song);
- if(!searchAuthor(result, author, numAuthors)) //se l'autore non viene trovato
- {
- newAuthor2(result, numAuthors, author); //aggiungo l'autore
- addSong(result[numAuthors], song); //aggiungo la canzone
- numAuthors++;
- }
- //l'autore è già presente
- else
- addSong(result[findAuthorNum(result, author, numAuthors)], song); //trovo la corrispondenza nell'array
- free(author);
- free(song);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement