再改进下上次的读入一行函数,利用zlib库的gzgtec函数读取文件,动态分配内存,最后没有多出空行。
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <string.h> 4 #include <zlib.h> 5 6 char *readlineGZ(gzFile file) 7 { 8 size_t baselen = 256; 9 char *line = (char *)malloc(sizeof(char) * baselen); 10 if(!line) exit(1); 11 12 size_t index = 0; 13 int ch; 14 while((ch=gzgetc(file)) != -1 && ch != 10) // 10 => " " 15 { 16 line[index] = ch; 17 index++; 18 19 if(index == baselen) 20 { 21 baselen += 128; 22 line = (char *)realloc(line,baselen); 23 if(line == NULL) 24 { 25 free(line); 26 exit(1); 27 } 28 } 29 } 30 31 line[index] = '