Prove pratiche 2016

From Sistemi Operativi
Jump to navigation Jump to search

Esame Pratico 22/01/2016

http://www.cs.unibo.it/~renzo/so/pratiche/2016.01.22.pdf

Esercizio 1

#include <stdlib.h>
#include <stdio.h>
#include <dirent.h>
#include <sys/types.h>
#include <string.h>
#include <unistd.h>

typedef struct nameNumber {
        char *name;
        int value;
} nameNumber;


int prefixToInt (char *string) {
    int i = 0;
    int num = 0;

    while (string[i] >= '0' && string[i] < '9' && i < strlen(string)) {
        num = (num*10) + (string[i]-'0');
        i++;
    }
    return num;

}

void fileSort(struct nameNumber **files) {

}

int comp (const void * el1, const void * el2) {
    struct nameNumber *f = *((nameNumber**)el1);
    struct nameNumber *s = *((nameNumber**)el2);
    if (f->value > s->value) return 1;
    if (f->value < s->value) return -1;
    return 0;
}

int main(int arg, char* argv[]) {
    struct nameNumber **files;

    DIR *dir;
    struct dirent *ent;

    int count = 0;

    if((dir = opendir(argv[1])) != NULL) 
    {
        while( (ent = readdir(dir)) != NULL ) 
        {   
            if (ent->d_name[0] < '9' && ent->d_name[0] >= '0') 
            {
                files = (struct nameNumber**)realloc(files , (count+1) * sizeof(struct nameNumber*));
                files[count] = (struct nameNumber*)malloc(sizeof(struct nameNumber));
                files[count]->name = (char*)malloc(sizeof(char)*strlen(ent->d_name) + 1);
                strcpy(files[count]->name, ent->d_name);
                files[count]->value = prefixToInt(files[count]->name);
                printf("name : %s  ,  value : %d\n", files[count]->name , files[count]->value);
                count++;
            }
        }
    }
    
    
    qsort(files, count, sizeof(nameNumber*), comp);

    int i;
    for (i=0; i < count; i++) {
        printf("%s\n",files[i]->name);
    }
   
}