![]() |
#2
rjsp2021-05-26 09:24
|

#include <zlib.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
char *getlines(gzFile file)
{
size_t baselen = 10;
char *line = (char *)malloc(baselen * sizeof(char));
if(!line) exit(1);
while(gzgets(file,line,baselen)!=NULL)
{
if(strstr(line,"\n")) // 判断读入的内容时候含有换行符,此处有'\n',表明完整的读完一行。
{
line[strlen(line)-1]='\0';
return line;
}
else // 没有读入换行符,只读入了一行的一部分; 此时重新分配内存,再次用gzgets读取, 直到读到换行符为止。
{
do
{
baselen += 10;
line = (char *)realloc(line,baselen);
if(!line) exit(1);
gzgets(file,line,baselen);
}while(strstr(line,"\n")==NULL);
line[strlen(line)-1]='\0';
return line;
}
}
line[strlen(line)-1]='\0';
return line;
}
int main(int argc, char *argv[])
{
gzFile fp=gzopen(argv[1],"r");
if(!fp) exit(1);
int cot =0;
char *line;
while((line=getlines(fp))!=NULL && !gzeof(fp))
{
cot++;
printf("line %d\t%s\n",cot,line);
free(line);
}
gzclose(fp);
exit(0);
}
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
char *getlines(gzFile file)
{
size_t baselen = 10;
char *line = (char *)malloc(baselen * sizeof(char));
if(!line) exit(1);
while(gzgets(file,line,baselen)!=NULL)
{
if(strstr(line,"\n")) // 判断读入的内容时候含有换行符,此处有'\n',表明完整的读完一行。
{
line[strlen(line)-1]='\0';
return line;
}
else // 没有读入换行符,只读入了一行的一部分; 此时重新分配内存,再次用gzgets读取, 直到读到换行符为止。
{
do
{
baselen += 10;
line = (char *)realloc(line,baselen);
if(!line) exit(1);
gzgets(file,line,baselen);
}while(strstr(line,"\n")==NULL);
line[strlen(line)-1]='\0';
return line;
}
}
line[strlen(line)-1]='\0';
return line;
}
int main(int argc, char *argv[])
{
gzFile fp=gzopen(argv[1],"r");
if(!fp) exit(1);
int cot =0;
char *line;
while((line=getlines(fp))!=NULL && !gzeof(fp))
{
cot++;
printf("line %d\t%s\n",cot,line);
free(line);
}
gzclose(fp);
exit(0);
}