I have some structs in my file and I have to sort them numerically (I have to sort the ID of students for example) I wrote this but it doesn't work :
int i = 0;
fseek(fileKALAJADIDptr, 0, SEEK_SET);
while (fread(&KJadid, sizeof(struct KalaJadid), 1, fileKALAJADIDptr))
{
int j = i + 1;
fseek(fileKALAJADIDptr2, j * sizeof(struct KalaJadid), SEEK_SET);
while (fread(&KJadid2, sizeof(struct KalaJadid), 1, fileKALAJADIDptr2))
{
if (KJadid.Tedad > KJadid2.Tedad)
{
struct KalaJadid swap = KJadid;
KJadid = KJadid2;
KJadid2 = swap;
fwrite(&KJadid2, sizeof(struct KalaJadid), 1, fileKALAJADIDptr2);
fseek(fileKALAJADIDptr, i * sizeof(struct KalaJadid), SEEK_SET);
fwrite(&KJadid, sizeof(struct KalaJadid), 1, fileKALAJADIDptr);
}
j++;
}
i++;
}
fclose(fileKALAJADIDptr);
fclose(fileKALAJADIDptr2);
first of all I point at the beginning of the file with fseek, then we have "while" for sorting ( I use selection sort ) but it doesn't work and I get run time error... what should I do?
openning file part :
FILE* fileKALAJADIDptr = fopen(fileKALAJADID, "r+b");
FILE* fileKALAJADIDptr2 = fopen(fileKALAJADID, "r+b");
if (fileKALAJADIDptr == NULL)
{
fopen(fileKALAJADID, "w+");
}
here's the code: https://code.sololearn.com/c8Bh9vtao0C0/#cpp
Hey guys I found my answer.. I had to copy data in a structure array and sort the array then rewriting file with sorted structure array.