|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 大裤衩子 于 2021-5-25 12:48 编辑
利用zlib库中的gzgets 读取一整行内容,没发现我的逻辑错误在哪里 ,输出总是有问题。
代码如下,请求大家帮助,谢谢!
- #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);
- }
复制代码
gcc -Wall -lz w.c -o ww ,输出结果只有最后的部分
你看看是不是函数用的不熟练,如果觉得函数用法有问题可以规避掉自己不会的函数
|
-
|