// Functions to read a network stored in a GML file into a NETWORK struct
//
// Mark Newman 11 AUG 06
//
// To use this software, #include "readgml.h" at the head of your program
// and then call the following.
//
// Function calls:
// int read_network(NETWORK *network, FILE *stream)
// -- Reads a network from the FILE pointed to by "stream" into the
// structure "network". For the format of NETWORK structs see file
// "network.h". Returns 0 if read was successful.
// void free_network(NETWORK *network)
// -- Destroys a NETWORK struct again, freeing up the memory
// Inclusions
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "network.h"
// Constants
#define LINELENGTH 1000
// Types
typedef struct line {
char *str;
struct line *ptr;
} LINE;
// Globals
LINE *first;
LINE *current;
// Function to read one line from a specified stream. Return value is
// 1 if an EOF was encountered. Otherwise 0.
int read_line(FILE *stream, char line[LINELENGTH])// line在这里为一个字符数组
{
if (fgets(line,LINELENGTH,stream)==NULL) return 1; //每次都读一行
line[strlen(line)-1] = '\0'; // Erase the terminating NEWLINE
return 0;
}
// Function to read in the whole file into a linked-list buffer, so that we
// can do several passes on it, as required to read the GML format
// efficiently
int fill_buffer(FILE *stream)
{
int length;
char line[LINELENGTH];
LINE *previous; //之前的指针
if (read_line(stream,line)!=0) {
first = NULL; // Indicates empty buffer
return 1;
}
length = strlen(line) + 1;
first = malloc(sizeof(LINE));//first 为指向第一个节点的指针
first->str = malloc(length*sizeof(char));
strcpy(first->str,line); //用于完成将读到到line字符串赋值到 LINE的链表中。
previous = first;
while (read_line(stream,line)==0) { //将GML文件的每一行存在以FIRST存放的链表中,而LINE结构体为链表的节点。
length = strlen(line) + 1; //而LINE结构体中的,str字符指针,用来连接读到到字符串,这里的加1是为了存放\0空字符。
previous->ptr = malloc(sizeof(LINE));
previous = previous->ptr;
previous->str = malloc(length*sizeof(char));
strcpy(previous->str,line);
}
previous->ptr = NULL; // Indicates last line //将最后一个节点的ptr的指向为空,说明链表到了尾点
return 0;
}
// Function to free up the buffer again
void free_buffer()
{
LINE *thisptr;
LINE *nextptr;
thisptr = first;
while (thisptr!=NULL) {
nextptr = thisptr->ptr;
free(thisptr->str); //释放thisptr所指向的字符串
free(thisptr); //释放LINE节点
thisptr = nextptr; //将thisptr释放后,thisptr向前移
}
}
//
gml文件格式解析程序详解之源文件
最新推荐文章于 2024-08-18 00:30:00 发布