[ create a new paste ] login | about

Link: http://codepad.org/cuj3eeQe    [ raw code | output | fork ]

C, pasted on May 26:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct Lib_node {
  void *data;
  struct Lib_node *left, *right;
};

void lib_init_list(struct Lib_node **root)
{
  *root = NULL;
}

void *lib_add_list(struct Lib_node **root, void *data, int (*cmp)(void *, void *))
{
  int c;
  struct Lib_node *node;

  if (*root == NULL) {
    if((node = malloc(sizeof(struct Lib_node))) == NULL) {
      fprintf(stderr, "cannot allocate enoutgh memory.\n");
      exit(-1);
    }
    node->data = data;
    node->left = node->right = NULL;
    *root = node;
    return data;
  }
  if ((c = (*cmp)(data, (*root)->data)) < 0) {
    return lib_add_list(&((*root)->left), data, cmp);
  } else if (c > 0) {
    return lib_add_list(&((*root)->right), data, cmp);
  } else {
    return (*root)->data;
  }
}

void *lib_delmin_list(struct Lib_node **root)
{
  void *data;
  struct Lib_node *p;

  if (*root == NULL)
    return NULL;
  if ((*root)->left != NULL)
    return lib_delmin_list(&((*root)->left));
  data = (*root)->data;
  p = *root;
  *root = p->right;
  free(p);
  return data;
}

int cmp(char *a, char *b)
{
  return strlen(b) - strlen(a);
}

void output(struct Lib_node **root)
{
  char *data;
  while ((data = lib_delmin_list(root)) != NULL) {
    printf("%s\n", data);
    free(data);
  }
}

#define BUFFSIZE 1024 /* >= 2 */
char *getline(FILE *fp)
{
  static char inbuff[BUFFSIZE];
  char *outbuff_malloc, *tmpbuff;
  char *p, *q;
  int fEOL;
  if ((outbuff_malloc = malloc(1)) == NULL)
    return NULL;
  *outbuff_malloc = '\0';
  fEOL = 0;
  do {
    if ((q = fgets(inbuff, BUFFSIZE, fp)) == NULL)
      break;
    for (p = inbuff; *p != '\0'; p++)
      ;
    if (*(p - 1) == '\n') {
      *(p - 1) = '\0';
      fEOL = 1;
    }
    if ((tmpbuff = realloc(outbuff_malloc, strlen(outbuff_malloc) + strlen(inbuff) + 1)) ==NULL) {
      free(outbuff_malloc);
      return NULL;
    }
    strcat(tmpbuff, inbuff);
    outbuff_malloc = tmpbuff;
  } while (!fEOL);
  if (q == NULL) {
    free(outbuff_malloc);
    return NULL;
  }
  return outbuff_malloc;
}

int main(int argc, char *argv[])
{
  char *inputLine_malloc;
  FILE *fp;
  struct Lib_node *root;
  
  if ((fp = fopen("file.txt", "r")) == NULL) {
    fprintf(stderr, "cannot open the file '%s'.\n", argv[1]);
    return -1;
  }
  lib_init_list(&root);
  while ((inputLine_malloc = getline(fp)) != NULL) {
    lib_add_list(&root, inputLine_malloc, (int (*)(void *, void *))cmp);
  }
  output(&root);
  fclose(fp);
  return 0;
}
/* end */


Output:
1
2
3
cannot open the file '(null)'.

Exited: ExitFailure 255


Create a new paste based on this one


Comments: