Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1326142
  • 博文数量: 268
  • 博客积分: 10698
  • 博客等级: 上将
  • 技术积分: 2867
  • 用 户 组: 普通用户
  • 注册时间: 2007-07-14 22:21
文章分类

全部博文(268)

文章存档

2012年(19)

2011年(13)

2010年(29)

2009年(26)

2008年(99)

2007年(82)

我的朋友

分类: C/C++

2008-05-09 06:22:22



/* 下面是两个方向的链表,从文件读取字符,一个按行,一个按列。*/
/* Linked lists in two directions */
/* Written by Myst Shen in May,2008 */

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

typedef struct data {
  char val;
  bool selected;
  struct data *next;
  struct data *next2;
}NODE;


NODE *head,*tail,*p;
FILE *fp;
int x, y, max, c;

/*The 1st linked list reads from the rows*/
NODE * init (void){
  head=(NODE *)malloc(sizeof(NODE));
  head->next = NULL;
  tail = head;
 
if ( (fp = fopen( "data", "r" )) == NULL ) {
    printf ("Cannot open this file.\n");
    exit(0);
  };

  while (1){
    c = fgetc(fp);
    if( c == EOF ) break;
    p=(NODE *)malloc(sizeof(NODE));
    p->val = c;
    p->selected = false;
    p->next = NULL;
    tail->next = p;
    tail = p;
  }
  return head;
}

/*The 2nd linked list reads from the columns*/
NODE * init2 (void){
  head=(NODE *)malloc(sizeof(NODE));
  head->next2 = NULL;
  tail = head;
  max = width();
  rewind(fp);
  y=0;
  for ( x=1; x<=max; x++ ) {
    while (1){
      y++;
      c = fgetc (fp);
      if ( c == EOF ) break;
      if ( y == x ) {
        p = (NODE *)malloc(sizeof(NODE));
        p->val = c;
        p->selected = false;
        p->next2 = NULL;
        tail->next2 = p;
        tail = p;
      }
      if ( c == '\n' ) y = 0;
    }
    p = (NODE *)malloc(sizeof(NODE));
    p->val = '\n';
    p->selected = false;
    p->next2 = NULL;
    tail->next2 = p;
    tail = p;
    rewind (fp);
    y=0;
  }
  fclose(fp);
  return head;
}

/*Get the width of the file*/
int width(void){
  rewind(fp);
  x = 0;
  max = 0;

  while (1){
    c=fgetc(fp);
    if ( c == '\n' ) {
      if ( max < x ) max = x;
      x=0;
      continue;
    }
    x++;
    if ( c == EOF) break;
  }
  return max;
}

/*Print the 1st linked list*/
void print1 (NODE *head){
  p = head;
  while(1){
    p = p->next;
    if ( p == NULL ) break;
    printf("%c", p->val);
  }
  putchar ('\n');
}

/*Print the 2nd linked list*/
void print2 (NODE *head){
  p = head;
  while(1){
    p = p->next2;
    if ( p == NULL ) break;
    printf("%c", p->val);
  }
  putchar ('\n');
}

void main(void){
  print1(init());
  print2(init2());
}

阅读(1428) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~