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 }
作者:天使不设防
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!