您好,欢迎来到化拓教育网。
搜索
您的当前位置:首页Linux系统编程-getline函数

Linux系统编程-getline函数

来源:化拓教育网

getline函数

getline函数实际是由malloc和realloc函数共同封装而成的,一开始用malloc分配一块空间,不够之后再用realloc函数扩充。

getline的用法

getline返回值

成功的话,返回getline成功读到的字符个数,包含分隔符,但不包含'\0'。

失败的话,返回值为-1。

代码实例1

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char **argv)
{
   FILE *fp;
   char *linebuf;
   size_t linesize;

   if (argc < 2)
   {
       fprintf(stderr, "Usage...\n");
       exit(1);
   }

   fp = fopen(argv[1], "r");

   if (fp == NULL)
   {
       perror("fopen()");
       exit(1);
   }
   
   /*!!!*/
   linebuf = NULL;
   linesize = 0;

   while(1)
   {
      	if (getline(&linebuf, &linesize, fp) < 0)
		break;
	printf("%zu\n", strlen(linebuf));
   }

   fclose(fp);

   exit(0);
}

要打开的makefile文件

运行结果:

一共两行,第一行45个字符,第二行1个字符。

代码实例2

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char **argv)
{
   FILE *fp;
   char *linebuf;
   size_t linesize;

   if (argc < 2)
   {
       fprintf(stderr, "Usage...\n");
       exit(1);
   }

   fp = fopen(argv[1], "r");

   if (fp == NULL)
   {
       perror("fopen()");
       exit(1);
   }
   
   /*!!!*/
   linebuf = NULL;
   linesize = 0;

   while(1)
   {
      	if (getline(&linebuf, &linesize, fp) < 0)
		    break;
	    printf("%zu\n", strlen(linebuf));
        printf("%zu\n", linesize);
   }

   fclose(fp);

   exit(0);
}

运行makefile文件,可以看出一开始malloc分配的内存为120。

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- huatuo9.cn 版权所有 赣ICP备2023008801号-1

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务