Write a program to read a binary file of integers, sort the integers and write them back into the same file.

Source Code

Brief explanation is provided after the source code.

#include <stdio.h>
#include <stdlib.h>

struct tnode{
    int number;
    struct tnode *left; /* left Child */
    struct tnode *right; /* right Child */
};

struct tnode *addtree(struct tnode*, int);
void treeprint(struct tnode*, FILE *out);
struct tnode *root;
struct tnode *talloc(void);
int *dupnum(int *);



int main(int argc, char **argv){
    FILE *in;
    const char * fn = "integer_file";
    char buff[0x200];
    root = NULL;  /* empty tree */

    if((in = fopen(fn,"rb+")) == NULL){
        printf("Cannot open input file.\n");
        exit(1);
    }

     // Read integers from a file and add to a tree node
    while (fgets(buff, sizeof buff, in)) {
        root = addtree(root, atoi(buff));
    }

    rewind(in); // Bring the file pointer back to the beginning of the file.
    treeprint(root, in);
    fclose(in);
    return 0;
}

/* addtree: add a node with n, at or below p */
struct tnode *addtree(struct tnode *p, int n){
    int cond;
    if (p == NULL){
        p = talloc();
        p -> number = dupnum(n);
        p -> left = p -> right = NULL;
    }else if (n <= p->number)
        p -> left = addtree(p -> left , n);
    else
        p -> right = addtree(p -> right , n);

    return p;
}


/* treeprint: in-order print of tree p */
void treeprint(struct tnode *p, FILE *out){

    if (p != NULL) {
        treeprint(p -> left ,out);    /* Begin with left sub tree */
        fprintf(out,"%d\n" ,p -> number);     /* Output number */
        treeprint(p -> right ,out);   /* then move to right sub tree */
    }
}

/* talloc: make a tnode */
struct tnode *talloc(void) {
    return (struct tnode *) malloc(sizeof(struct tnode)); 
}

/* duplicate a number */
int *dupnum(int *n){
    char *p;
    /* make a duplicate of n */
    p = (int *) malloc(sizeof(int));
    if(p != NULL)
        p = n;
    return p;
    free(p);
}

Content of file before sorting

100
-1
10
-6
12
10
23
-7

Content of file after sorting

-7
-6
-1
10
10
12
23
100

Brief Explanation

  • The file fn is opened in binary mode for reading/writing using the function fopen.
  • Each number in the file is added to a node on a binary tree using the function addtree
  • The nodes are maintained so that at any node the left subtree contains only numbers that are less than or equal the number at the node, and the right subtree contains only numbers that are greater.
  • The tree is then printed using in order traversal to the same file. By using in order traversal, the numbers will be sorted.

Add comment


Security code
Refresh