I have a textfile with name followed by a number that is the priority of the name, now I'm trying to sort the textfile by priority and write a new file.
old
name1 1
name2 2
name3 3
name4 1
name5 1
name6 2
name7 1
name8 3
new
name 1 1
name4 1
name5 1
name2 2
name6 2
name3 3
name8 3
I have achieved to get the old textfile in an array, but I'm stuck with sorting that array by priority. I shouldn't loop through the file again, just wanna sort the array then write that new sorted array to a new text file. How should I proceed??
The code
#include <stdio.h>
#include <stdlib.h>
typedef struct{
int p;
char *name;
}names;
int main(void){
FILE *old= fopen("old.txt", "r");
FILE *new = fopen("new.txt", "w");
char n[10];
int i =0;
names *name= malloc(sizeof(names));
for(i; i<count; i++){
int p;
char *n= malloc(sizeof(char) * 4);
fscanf(old, "%s %i", n, &p);
names[i].name= n;
names[i].p= p;
}
int j=0;
for(i=0; i < count;i++){
}
return 0;
}
fscanf(eerste, "%s %f", name, &prio);, be careful,priois anintand you are scanning afloatjobas{ int prio; char jobName[8]; }; not having to deal with a separatemalloc()just for the (very short) string will make it both easier and faster.