C语言 自定义函数按行读入文件2

再改进下上次的读入一行函数,利用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 => "\n"
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] = '\0'; // trans raw line's \n to \0 , while loop index++ already 
32 
33     if(ch == -1)  // end of file
34     {
35         return NULL;
36     }
37     return line;
38 }
39 
40 int main(int argc, char *argv[])
41 {
42     if(argc != 2)
43     {
44         fprintf(stderr,"usage: %s <text file>[.gz]\n",argv[0]);
45         exit(1);
46     }
47 
48     gzFile fp=gzopen(argv[1],"rb");
49     if(!fp) exit(1);
50     
51     for(char *line; line=readlineGZ(fp),line; )
52     {
53         fprintf(stdout,"%s\n",line);
54         free(line);
55     }
56 
57     exit(0);
58 }

 

posted @ 2020-11-10 15:37  天使不设防  阅读(145)  评论(0编辑  收藏  举报