#include #include #include #include /* * ***esercizio B11*** il programma legge da stdin una riga alla volta fino a EOF una volta lette tutte le righe, fa il sort in ordine crescente delle righe; scrive le righe ordinate su stdout vedere esempi: https://github.com/marcotessarotto/exOpSys/blob/master/041qsortstr/qsortstr.c https://github.com/marcotessarotto/exOpSys/blob/master/046getline/getline.c */ static int cmpstringp(const void *p1, const void *p2) { /* The actual arguments to this function are "pointers to pointers to char", but strcmp(3) arguments are "pointers to char", hence the following cast plus dereference */ return strcmp(* (char * const *) p1, * (char * const *) p2); } // tratto da: // https://github.com/marcotessarotto/exOpSys/blob/master/046getline/getline.c #define CHUNK_SIZE 32 // legge da fd una linea intera (fino a che incontra carattere newline oppure EOF oppure errore in lettura da fd) // newline è incluso nella stringa di caratteri restituita; la stringa è terminata da \0 // scrive in *buffer l'indirizzo del buffer allocato // scrive in *n la dimensione del buffer; restituisce n // se ha raggiunto EOF, scrive 1 in *eof // se read ha restituto errore, scrive -1 in *eof int my_getline(int fd, char ** buffer, size_t * n, int * eof) { char * buf; size_t size; int pos = 0; char ch; int res; if (buffer == NULL) { return -1; } buf = calloc(CHUNK_SIZE, sizeof(char)); size = CHUNK_SIZE; while ((res = read(fd, &ch, 1)) == 1) { // read restituisce 0 in caso di EOF, -1 se errore if (pos == size) { size += CHUNK_SIZE; buf = realloc(buf, size); } buf[pos++] = ch; if (ch == '\n') { break; } } if (res == -1) { perror("read"); if (eof != NULL) *eof = -1; } else if (res == 0) { // EOF if (eof != NULL) *eof = 1; } else { if (eof != NULL) *eof = 0; } if (pos == size) { size += 1; buf = realloc(buf, size); } buf[pos++] = '\0'; // end of string if (pos < size) buf = realloc(buf, pos); *buffer = buf; if (n != NULL) *n = pos; return pos; } int main(int argc, char * argv[]) { //char * buf; size_t n; char ** lines; size_t lines_len = 1; lines = realloc(NULL, lines_len * sizeof(char *)); if (lines == NULL) { perror("realloc"); exit(1); } int pos = 0; int eof = 0; while (!eof) { my_getline(STDIN_FILENO, &lines[pos], &n, &eof); pos++; if (pos == lines_len) { lines_len = lines_len * 2; lines = realloc(lines, lines_len * sizeof(char *)); } } pos--; printf("ho letto %d righe\n\n", pos); printf("linee non ordinate:\n"); for (int i = 0; i < pos; i++) { printf("line %d: %s", i, lines[i]); } printf("\n"); qsort(lines, pos, sizeof(char *), cmpstringp); printf("linee ordinate:\n"); for (int i = 0; i < pos; i++) { printf("line %d: %s", i, lines[i]); } /* il programma legge da stdin una riga alla volta fino a EOF una volta lette tutte le righe, fa il sort in ordine crescente delle righe; scrive le righe ordinate su stdout */ return 0; }