0

Ok, so I have a file with integers, like:

14
22
82
53
61
74
47
95

and I want to copy it into my structure, the problem being that my structure has 2 columns, and I don't know how to copy the file into just one.

My question is: is there a quick and easy function like qsort that will automatically copy my file over?

 #include <stdio.h>      /* printf */
 #include <stdlib.h>     /* qsort */

struct Element
{
int userId;
int score;
};

struct Element elements[] = { 
{1, 13},
{2,  9},
{3, 13},
{4, 19},
{5,  8},
{6, 11},
{7, 14},
{8, 17},
};

int ascendingSortCompareFunction (const void * a, const void * b)
{
   return (((struct Element *)a)->score - ((struct Element *)b)->score);
}

int descendingSortCompareFunction (const void * a, const void * b)
{
   return ((struct Element *)b)->score) - (((struct Element *)a)->score;
}

int main ()
{
int n;
int count;

count = sizeof(elements) / sizeof(elements[0]);

qsort(elements, count, sizeof(elements[0]), ascendingSortCompareFunction);
printf ("UserID\tScore (Ascending Sort)\n");
for (n = 0 ; n < count ; n++)
    printf ("%d\t%d\n", elements[n].userId, elements[n].score);

qsort(elements, count, sizeof(elements[0]), descendingSortCompareFunction);
printf ("UserID\tScore (Descending Sort)\n");
for (n = 0 ; n < count ; n++)
    printf ("%d\t%d\n", elements[n].userId, elements[n].score);

getchar();

return 0;
}

2 Answers2

1

Not sure if there's a function available but it doesn't take much code to do it manually.

You open the file:

FILE *fp;
fp = fopen("myfile.txt", "r")

Then loop and read the file one line at a time, and insert each int into the struct array:

//looping through file and array with i as a counter
fscanf(fp,"%d", &elements[i].score);

This assumes that you are reading the scores from your file. That hopefully is enough to get you started!

Oh, and close the file after:

fclose(fp);
Neil Neyman
  • 2,116
  • 16
  • 21
0

I am almost sure that this is what you are looking for

#include <stdio.h>      /* printf */
#include <stdlib.h>     /* qsort */

struct Element
{
    int userId;
    int score;
};

int ascendingSortCompareFunction (const void * a, const void * b)
{
   return (((struct Element *)a)->score - ((struct Element *)b)->score);
}

int descendingSortCompareFunction (const void * a, const void * b)
{
   return -ascendingSortCompareFunction(a, b);
}

void readFromFile(const char *const filename,  struct Element **elements, size_t *count)
{
    FILE *file;
    void *auxiliary;
    int   index;
    int   score;
    char  line[128];

    if ((elements == NULL) || (count == NULL))
        return;
    *count    = 0;
    *elements = NULL;
    file      = fopen(filename, "r");
    if (file == NULL)
        return;

    index = 0;
    while (fgets(line, sizeof(line), file) != NULL)
    {
        if (sscanf(line, "%d", &score) == 1)
        {
            auxiliary = realloc(*elements, (1 + *count) * sizeof(struct Element));
            if (auxiliary == NULL)
            {
                free(*elements);
                fclose(file);

                *elements = NULL;

                return;
            }
            *elements                  = auxiliary;
            (*elements)[*count].userId = 1 + index;
            (*elements)[*count].score  = score;

            *count += 1;
            index  += 1;
        }
    }
    fclose(file);
}

int main ()
{
    size_t          count;
    size_t          n;
    struct Element *elements;
    size_t          size;

    elements = NULL;
    size     = sizeof(struct Element);
    count    = 0;

    readFromFile("/home/iharob/file.txt", &elements, &count);
    if ((elements != NULL) && (count > 0))
    {
        qsort(elements, count, size, ascendingSortCompareFunction);
        printf ("UserID\tScore (Ascending Sort)\n");

        for (n = 0 ; n < count ; n++)
            printf ("%d\t%d\n", elements[n].userId, elements[n].score);

        qsort(elements, count, size, descendingSortCompareFunction);
        printf ("UserID\tScore (Descending Sort)\n");

        for (n = 0 ; n < count ; n++)
            printf ("%d\t%d\n", elements[n].userId, elements[n].score);

        free(elements);
    }
    getchar();

    return 0;
}
Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
  • 1
    after this line: '*elements = NULL;' there needs to be a line: '*count = 0;' – user3629249 Jan 02 '15 at 23:04
  • @user3629249 wow that was a very stupid mistake. Although `count` is initialized in `main()` and hence there was no error, but it's better to initialize it in `readFromFile()`. – Iharob Al Asimi Jan 02 '15 at 23:40