X-Git-Url: https://git.llucax.com/z.facultad/75.06/emufs.git/blobdiff_plain/6a1699c5c4c2ba05db94118fe15188372ab7d37e..d85375b5ea6773eb12e86e630961034cd5df1e96:/emufs/external_sort/mergefile.c diff --git a/emufs/external_sort/mergefile.c b/emufs/external_sort/mergefile.c index 2d59fb1..f5bf0b0 100644 --- a/emufs/external_sort/mergefile.c +++ b/emufs/external_sort/mergefile.c @@ -41,51 +41,18 @@ #include #include -char* mergefile_makefilename(int i) -{ - size_t size = sizeof(MERGEFILE_TEMPLATE) + 8; /* 8 más para el int */ - char* filename = malloc(size); - if (!filename) return 0; - /* Hasta que me de la memoria para crear el nombre del archivo */ - while (snprintf(filename, size, MERGEFILE_TEMPLATE, i) >= size) { - char* new; - size += 8; - new = realloc(filename, size); - if (new) { - filename = new; - } else { - free(filename); - return 0; - } - } - return filename; -} - -MERGEFILE* mergefile_new(int i) +MERGEFILE* mergefile_new() { MERGEFILE* mf = malloc(sizeof(MERGEFILE)); if (!mf) { return 0; } - /* asigno el nombre de archivo */ - if (!(mf->filename = mergefile_makefilename(i))) { - free(mf); - return 0; - } /* abre archivo */ - if (!(mf->fp = fopen(mf->filename, "rb"))) { - free(mf->filename); - free(mf); - return 0; - } - /* obtiene dato */ - if (fscanf(mf->fp, "%i", &(mf->next)) <= 0) { - fclose(mf->fp); - free(mf->filename); + if (!(mf->fp = tmpfile())) { free(mf); return 0; } - mf->more = 1; + mf->more = 0; return mf; } @@ -93,22 +60,27 @@ void mergefile_delete(MERGEFILE* mf) { assert(mf); assert(mf->fp); - assert(mf->filename); fclose(mf->fp); - remove(mf->filename); - free(mf->filename); free(mf); } -int mergefile_peek_next(MERGEFILE* mf) +int mergefile_switch_to_input(MERGEFILE* mf) +{ + /* obtiene dato, debe tener al menos uno para ser un mergefile */ + if (fseek(mf->fp, 0L, SEEK_SET)) return 0; + if (fscanf(mf->fp, "%i", &(mf->next)) <= 0) return 0; + mf->more = 1; + return 1; /* OK */ +} + +int mergefile_push(MERGEFILE* mf, int data) { assert(mf); assert(mf->fp); - assert(mf->more); - return mf->next; + return fprintf(mf->fp, "%i\n", data); } -int mergefile_pop_next(MERGEFILE* mf) +int mergefile_pop(MERGEFILE* mf) { int ret; assert(mf); @@ -120,6 +92,14 @@ int mergefile_pop_next(MERGEFILE* mf) return ret; } +int mergefile_peek(MERGEFILE* mf) +{ + assert(mf); + assert(mf->fp); + assert(mf->more); + return mf->next; +} + int mergefile_has_more(MERGEFILE* mf) { assert(mf);