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.
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.