zoukankan      html  css  js  c++  java
  • 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 => "
    "
    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] = ''; // trans raw line's 
     to  , 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]
    ",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
    ",line);
    54         free(line);
    55     }
    56 
    57     exit(0);
    58 }
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利.
  • 相关阅读:
    软件使用[17]
    软件使用[20]
    软件使用[12]
    软件使用[10]
    软件使用[22]
    软件使用[06]
    软件使用[11]SlickEdit
    软件使用[19]
    uva 10717【Mint】
    uva 10791【 Minimum Sum LCM】
  • 原文地址:https://www.cnblogs.com/mmtinfo/p/13954101.html
Copyright © 2011-2022 走看看