0

egen.h

typedef struct postTyp
{
    char namn[30];
    char efternamn[30];
    char klubb[30];
}postTyp;

FILE *openfil();

startordning.h

#define MAX_SKIERS 100
typedef struct nummer
{
    int skiers[MAX_SKIERS];
    int pos1;
    int pos2;
    int temp;
}nummer;

FILE *openfil();

tid.h

typedef struct tid
{
    float tid[10];
}tid;

FILE *openfil();

main.c

#include "egen.h"
#include "startordning.h"
#include "tid.h"

void registrera(int x) {
    FILE *fp;
    char filnamn[] = "test.dat";

    postTyp post;
    fp = openfil(filnamn, filnamn, filnamn);  
    if(fp==NULL){
        exit(1);
    }

fseek(fp, 0, SEEK_SET); // går först i filen
fread(&post, sizeof(postTyp), 1, fp); // läser av filen
while(!feof(fp)){
fread(&post, sizeof(postTyp), 1, fp); //läser av filen om det är sant
x++;
}

while (x < 3) {

    fseek(fp, 0, SEEK_END);
    printf("\nAnge namn: ");
    gets(post.namn);
    printf("Ange efternamn: ");
    gets(post.efternamn);
    printf("Ange klubb: ");
    gets(post.klubb);

fwrite(&post, sizeof(postTyp), 1, fp);
fseek(fp, 0, SEEK_SET);
fread(&post, sizeof(postTyp), 1, fp);
while(!feof(fp)){
        //printf("\n%s %s %s\n", post.namn, post.efternamn, post.klubb);
fread(&post, sizeof(postTyp), 1, fp);
}
x++;
}
fclose(fp);
}

void Copy() {

FILE *fptr1, *fptr2;
    char c;

    // Open one file for reading
    fptr1 = fopen("test.dat", "r");
    if (fptr1 == NULL)
    {
        exit(0);
    }

    // Open another file for writing
    fptr2 = fopen("test2.dat", "w");
    if (fptr2 == NULL)
    {
        exit(0);
    }

    // Read contents from file
    c = fgetc(fptr1);
    while (c != EOF)
    {
        fputc(c, fptr2);
        c = fgetc(fptr1);
    }

    fclose(fptr1);
    fclose(fptr2);

    //printf("\ncopy succesful\n");
}

void startordning(int x) {

FILE *fp;
    char filnamn[] = "test.dat";
postTyp post;
    fp = openfil(filnamn, filnamn, filnamn); 
    if(fp==NULL){
        exit(1);
    }

fseek(fp, 0, SEEK_SET); // går först i filen
fread(&post, sizeof(postTyp), 1, fp); // läser av filen
while(!feof(fp)){
fread(&post, sizeof(postTyp), 1, fp); //läser av filen om det är sant
x++;
}

nummer j;

   srand(time(NULL));
int i;


   for (i = 0; i <= x; i++){
      j.skiers[i] = i;
   }
   for (i = 0; i < x*2; i++) {
      // Generate two random positions
      j.pos1 = rand() % x + 1;
      j.pos2 = rand() % x + 1;

      // Swap the skiers at the two positions
      j.temp = j.skiers[j.pos1];
      j.skiers[j.pos1] = j.skiers[j.pos2];
      j.skiers[j.pos2] = j.temp;
   }

fseek(fp, 0, SEEK_SET);
fread(&post, sizeof(postTyp), 1, fp);
i=1;
while(!feof(fp)){
    printf("\n\n%s %s %s %d", post.namn, post.efternamn, post.klubb, j.skiers[i]);
fread(&post, sizeof(postTyp), 1, fp);
//printf(" %d", j.skiers[i]);
i++;
}

}

void aktider(int x) {

FILE *fp;
    char filnamn[] = "test2.dat";
postTyp post;
nummer j;
tid w;
    fp = openfil(filnamn, filnamn, filnamn); 
    if(fp==NULL){
        exit(1);
    }

int i;


fseek(fp, 0, SEEK_SET);
fread(&post, sizeof(postTyp), 1, fp);
i=1;
while(!feof(fp)){
    printf("\n\n%s %s %s %d", post.namn, post.efternamn, post.klubb, j.skiers[i]);
fread(&post, sizeof(postTyp), 1, fp);
//printf(" %d", j.skiers[i]);
i++;
x++;
}





 int p = 0;
 int number;

 while(p < 3) {

  printf("\nEnter startnumber on the one you wanna give a time to!\n");
  scanf("%d", &number);

  for (i = 0; i < x + 1; i++) 
  {
    if (j.skiers[i] == number)    /* If required element is found */
    {
      printf("What time do you wanna give the person?\n");
      scanf("%f", &w.tid[i]);
      p++;
      break;
    }
  }
 }

 fseek(fp, 0, SEEK_SET);
fread(&post, sizeof(postTyp), 1, fp);
i=1;
while(!feof(fp)){
    printf("\n\n%s %s %s %d %.2f", post.namn, post.efternamn, post.klubb, j.skiers[i], w.tid[i]);
fread(&post, sizeof(postTyp), 1, fp);
//printf(" %d", j.skiers[i]);
//printf(" %.2f ", w.tid[i]);
i++;
}

}

int main(int argc, const char* argv[]){
int x = 0;

    registrera(x);
    Copy();
    startordning(x);
    aktider(x);

return 0;

}

FILE *openfil(char namn[], char efternamn[], char klubb[]) {
    FILE *fpLokal;

    if((fpLokal = fopen(namn, "r+b")) == NULL)

    if ((fpLokal = fopen(namn, "w+b")) == NULL) {
        printf("fel\n");
        return NULL;
    }

    return fpLokal;
}

Above is my code and it works completly fine.It is currently printing this for example from a textfile

Hanna Svensson FCB 2 35.37
Patrik Svensson FCB 3 56.23
Oscar Svensson FCB 1 30.20

What I wanted to do next is sort the textfile so it printed like this instead

Oscar Svensson FCB 1 30.20
Hanna Svensson FCB 2 35.37
Patrik Svensson FCB 3 56.23

But whatever i do i smiply can't accheive this. Any tips on how I may accomplish this? Sry for the long post.

  • 2
    You could store all your input values in an array before writing the file, sort it with `qsort`, then do the writing. – Matteo Pinna Jan 03 '21 at 12:31
  • 1
    The file contents you show is indeed in text form. But you open and read the file as a raw binary file. That will most certainly not work well together. – Some programmer dude Jan 03 '21 at 12:40
  • 2
    There are also many other problems in the code you show, for example mismatching declaration and definition of `openFil`. Or that you read characters with [`fgetc`](https://en.cppreference.com/w/c/io/fgetc) into a `char` variable and then compare it to an `int` value (`EOF` is an `int`) and that might not work very well. And also [don't use `while (feof(...))` loops](https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong). And of course the inconsistent indentation and formatting making the code hard to read and understand. And probably more. – Some programmer dude Jan 03 '21 at 12:43
  • 2
    Looking at the man page for `gets` in the description it begins with `Never use this function.` – Bo R Jan 03 '21 at 12:50
  • Ok thanks for all your comments, I will try to fix the problems and try to use qsort to see if i can fix my problem. – lucke111222 Jan 03 '21 at 12:58
  • There's no need to seek to the beginning of a file right after you open it. I'm seeing that practice a lot lately. Who is teaching that? – William Pursell Jan 03 '21 at 14:34

1 Answers1

0

Try to restructure your concept of the information you are handling. Once that is in a structure manner applicy something qsort will make sorting the database a breeze. See example file below:

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

struct recordType
{
   char forename[30];
   char surname[30];
   char clubname[30];
};

struct skierFileformat
{
   struct recordType post;
   int start_position;
   float tid;
};

void print_skiers(struct skierFileformat (*arr)[3])
{
   for(int i = 0; i < 3; ++i)
      printf(
         "%s %s %s %d %f\n",
         (*arr)[i].post.forename,
         (*arr)[i].post.surname,
         (*arr)[i].post.clubname,
         (*arr)[i].start_position,
         (*arr)[i].tid);
}

int cmp_start_pos(void const* a, void const* b)
{
   struct skierFileformat const* left  = (struct skierFileformat const*) a;
   struct skierFileformat const* right = (struct skierFileformat const*) b;
   if(left->start_position < right->start_position)
      return -1;
   if(right->start_position < left->start_position)
      return 1;
   return 0;
}

void sort_on_start_pos(struct skierFileformat (*arr)[3])
{
   qsort(*arr, 3, sizeof(struct skierFileformat), cmp_start_pos);
}

int cmp_tid(void const* a, void const* b)
{
   struct skierFileformat const* left  = (struct skierFileformat const*) a;
   struct skierFileformat const* right = (struct skierFileformat const*) b;
   if(left->tid < right->tid)
      return -1;
   if(right->tid < left->tid)
      return 1;
   return 0;
}

void sort_on_tid(struct skierFileformat (*arr)[3])
{
   qsort(*arr, 3, sizeof(struct skierFileformat), cmp_tid);
}


int main(void)
{
   FILE* dbHandle = fopen("thedatabase.bin", "rb");
   if(dbHandle == NULL)
   {
      fprintf(stderr, "Unable to open the database. Aborting.\n");
      return EXIT_FAILURE;
   }
   // for simplicity I "know" there are 3 entries
   struct skierFileformat all_skiers[3] = {0};
   if(fread(all_skiers, sizeof *all_skiers, 3, dbHandle) != 3)
   {
      fprintf(stderr, "Missing entries in the database. Aborting.\n");
      fclose(dbHandle);
      return EXIT_FAILURE;
   }
   printf("Content before sort:\n");
   print_skiers(&all_skiers);
   sort_on_start_pos(&all_skiers);
   printf("Content after sort on start position:\n");
   print_skiers(&all_skiers);
   sort_on_tid(&all_skiers);
   printf("Content after sort on tid:\n");
   print_skiers(&all_skiers);
   fclose(dbHandle);
   return EXIT_SUCCESS;
}
Bo R
  • 2,334
  • 1
  • 9
  • 17