Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

another qsort

Status
Not open for further replies.

Setzer

Programmer
Jan 5, 2002
9
RO

I need a function like qsort() wich doesnt need the size of the elements to be sorted( because they vary). If you ever heard of such a function or if u have some algoritm for it post an answer, pls.
 
you could use fseek() to deternim the number of records on file if the file is binary. Or open the file and count the number of records on file.

binary.

struct person {
char name[20];
char address[60];
};

int main void()
{
long count, no_recs;
struct person *people;
FILE fp;

fp = fopen("yourfile","rb")
fseek(fp, 0L, SEEK_END);
no_recs = ftell(fp)/sizeof(struct persons);
fseek(fp, 0L, SEEK_SET);
/* NO_RECS NOW HAS NUMBER OF RECORDS ON FILE */
people = (struct persons*)malloc(sizeof(struct persons) * no_recs);
/* rest of your code */

text file.

struct person {
char name[20];
char address[60];
};

int main void()
{
long count, no_recs = 0;
struct person *people;
char string[sizeof(struct persons)];
FILE fp;
/* I assume here that the file has each record stored*/
/* on file ending in new line character */
fp = fopen("yourfile","rt")
while((fscanf(fp,"%[^\n]\n", string))!=EOF)
no_recs++;
rewind(fp); /*reset file pointer */
/* NO_RECS NOW HAS NUMBER OF RECORDS ON FILE */
people = (struct persons*)malloc(sizeof(struct persons) * no_recs);
Hoping to get certified..in C programming.
 
for sorting structures of various sizes, place your structure into a union.
struct a {
/*your members*/
};
struct b {
/*your members*/
};

typedef union {
struct a membersofa;
struct b membersofb;
}MYUNION;

it doesnot matter which of the two structures is the larger as the union will always be as big as the largest member of the union.

UNION *myunion;

int main void()
{
long count, no_recs;
FILE fp;

fp = fopen("yourfile","rb")
fseek(fp, 0L, SEEK_END);
no_recs = ftell(fp)/sizeof(UNION);
fseek(fp, 0L, SEEK_SET);
/* NO_RECS NOW HAS NUMBER OF RECORDS ON FILE */
people = (UNION*)malloc(sizeof(UNION) * no_recs);
/* rest of your code */ Hoping to get certified..in C programming.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top