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⤋