gml文件格式解析程序详解之源文件

// 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向前移
  }
}




//
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值