English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

I have student data (name,idnumber,grade) I need to be able to sort the data alphabeticaly by name.

2006-08-10 08:50:23 · 1 answers · asked by tru_story 4 in Computers & Internet Programming & Design

1 answers

Hope it helps someone,

#include
#include
#include

#define LINE_LEN 128

typedef struct T
{
char *data;
struct T *left;
struct T *right;
} node;

node *makeNode (char *data)
{
node *temp = (node *) malloc (sizeof (node));

temp->data = calloc (LINE_LEN, sizeof (char));
strcpy (temp->data, data);
temp->left = NULL;
temp->right = NULL;

return temp;
}

node *addNode (char *line, node *root)
{
if (root == NULL)
return makeNode (line);

if (strcmp (line, root->data) < 0)
root->left = addNode (line, root->left);
else
root->right = addNode (line, root->right);

return root;
}

node *readFile (FILE *in_fp)
{
node *root = NULL;
char *line = (char *) calloc (LINE_LEN, sizeof (char));

while (!feof (in_fp))
{
fscanf (in_fp, "%s", line);
root = addNode (line, root);
}

return root;
}

void writeFile (node *root, FILE *out_fp)
{
if (root->left != NULL)
writeFile (root->left, out_fp);

fprintf (out_fp, "%s\n", root->data);

if (root->right != NULL)
writeFile (root->right, out_fp);
}

void sort (char *in, char *out)
{
FILE *in_fp = fopen (in, "r");
FILE *out_fp = fopen (out, "w");
node *root = readFile (in_fp);

writeFile (root, out_fp);
fclose (in_fp);
fclose (out_fp);
}

int main (int argc, char **argv)
{
if (argc != 3)
printf ("Usage: sort unsorted_filename sorted_filename\n");
else
sort (argv [1], argv [2]);

return 0;
}

2006-08-10 08:58:17 · answer #1 · answered by VzjrZ 5 · 0 0

fedest.com, questions and answers