[ create a new paste ] login | about

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

C, pasted on Nov 21:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

struct dlist {
  char *text;
  struct dlist *next;
  struct dlist *before;
};

void add_text(struct dlist **root, char *text) {
  struct dlist *p;
  if ((p = malloc(sizeof(struct dlist))) == NULL) {
    fprintf(stderr, "cannot allocate enough memory, aborted.\n");
    exit(-1);
  }
  p->text = text;
  if (*root == NULL) {
    *root = p;
    p->next = p;
    p->before = p;
    return;
  }
  p->next = *root;
  p->before = (*root)->before;
  (*root)->before->next = p;
  (*root)->before = p;
  *root = p;
}

char *get_text(struct dlist **root) {
  char *text;
  struct dlist *p;
  if (*root == NULL)
    return NULL;
  if ((*root)->next == (*root)) {
    text = (*root)->text;
    free(*root);
    *root = NULL;
    return text;
  }
  p = (*root)->before;
  p->before->next = p->next;
  p->next->before = p->before;
  text = p->text;
  free(p);
  return text;
}

#define ROW 24
#define COL 80
int main(int argc, char *argv[]) {
  static char buff[COL + 1];
  struct dlist *root;
  int i, c;
  char *p;
  FILE *fp;
  if (argc != 2) {
    fprintf(stderr, "usage: %s <file>\n", argv[0]);
    exit(-1);
  }
  if ((fp = fopen(argv[1], "rt")) == NULL) {
    fprintf(stderr, "%s: cannot open the file \'%s\'.\n", argv[0], argv[1]);
    exit(-1);
  }
  root = NULL;
  while (fgets(buff, COL + 1, fp) != NULL) {
    for (p = buff; *p != '\0'; p++)
      ;
    if (*(p - 1) == '\n')
      *(p - 1) = '\0';
    p = malloc(strlen(buff) + 1);
    strcpy(p, buff);
    add_text(&root, p);    
  }
  for (;;) {
    for (i = 0; i < ROW; i++) {
      p = get_text(&root);
      if (p == NULL)
        break;
      printf("%s\n", p);
    }
    if (p == NULL)
      break;
    if ((c = getchar()) == 'q')
      break;
  }
  while ((p = get_text(&root)) != NULL)
    free(p);
  return 0;
}
/* end */


Output:
1
2
3
usage: /t <file>

Exited: ExitFailure 255


Create a new paste based on this one


Comments: