Mehdi
Mehdi

Reputation: 2228

Sort numbers from file in C

I want to sort a file number by quick sort without using array. However, I don't know how can I replace a number at a specific position with another. I'm starting by making this code:

int main()
{  

FILE* F1=fopen("file.txt","r+");
  int var1, var2, min;

while(fscanf(F1, "%d", &var1) ==1){
                min = var1;
                long pos1 = ftell(F1);
                fseek(F1, 0, SEEK_SET);
        while(fscanf(F1, "%d", &var2) ==1){
            if(min > var2)
            {
               //Replace the var2 by min in the file

            }

        }
        fseek(F1, pos1, SEEK_SET);
}

}

Please, it is possible ?

Upvotes: 1

Views: 1376

Answers (1)

Ray Hamel
Ray Hamel

Reputation: 1309

There's no reasonable way to do it without using an array. Here's what I would do:

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#ifndef ENOENT
#define ENOENT 2
#endif

static int comp(const void *a, const void *b)
{
        const int va = *(const int *)a;
        const int vb = *(const int *)b;

        return va > vb ? 1 : va == vb ? 0 : -1;
}

int main(int argc, char **argv)
{
        enum {PAGE_SIZE = 4096, INTS_PER_PAGE = PAGE_SIZE / sizeof(int)};

        int *arr = (int *)malloc(PAGE_SIZE);
        int *beg = arr;
        int *end = arr;
        size_t arr_size = 0;
        size_t max_arr_size = INTS_PER_PAGE;
        FILE *f;

        if (arr == NULL) {
                perror("malloc(3)");
                return errno;
        }

        if (argc < 2) {
                fprintf(stderr, "%s\nusage: kwiksort input_file\n",
                        strerror(ENOENT));
                return ENOENT;
        }

        f = fopen(argv[1], "r+");

        if (f == NULL) {
                perror("fopen(3)");
                return errno;
        }

loop:
        for (; arr_size < max_arr_size; ++arr_size, ++end)
                if (fscanf(f, "%d", end) == EOF)
                        goto sort;

        max_arr_size += INTS_PER_PAGE;
        arr = (int *)realloc(arr, max_arr_size * sizeof(int));

        if (arr == NULL) {
                perror("realloc(3)");
                return errno;
        }

        beg = arr;
        end = arr + arr_size;

        goto loop;

sort:
        qsort(arr, arr_size, sizeof(int), comp);

        rewind(f);

        while (beg < end)
                fprintf(f, "%d\n", *beg++);

        fclose(f);
        free(arr);

        return 0;
}

Upvotes: 2

Related Questions