/* 下面是两个方向的链表,从文件读取字符,一个按行,一个按列。*/
/* 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());
}
|