getline函数使用

/*  
*    int getline(char **lineptr, size_t *n, FILE *stream)
*    
*    失败:成功返回读取的该行的字符数,返回-1。
*    参数:
*            lineptr:指向存放该行字符的指针,如果是NULL,则有系统帮助malloc,
*                       请在使用完成后free释放。
*            n:如果是由系统malloc的指针,填0
*            stream:文件指针
*/

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <errno.h>

/* Read up to (and including) a newline from STREAM into *LINEPTR
   (and null-terminate it). *LINEPTR is a pointer returned from malloc (or
   NULL), pointing to *N characters of space.  It is realloc'd as
   necessary.  Returns the number of characters read (not including the
   null terminator), or -1 on error or EOF.  */

int my_getline(char **lineptr, size_t *n, FILE *stream)
{
    static char line[256];
    char *ptr;
    unsigned int len;

   if (lineptr == NULL || n == NULL)
   {
      errno = EINVAL;
      return -1;
   }

   if (ferror (stream))
      return -1;

   if (feof(stream))
      return -1;
     
   fgets(line,256,stream);

   ptr = strchr(line,'\n');   
   if (ptr)
      *ptr = '\0';

   len = strlen(line);
   
   if ((len+1) < 256)
   {
      ptr = realloc(*lineptr, 256);
      if (ptr == NULL)
         return -1;
      *lineptr = ptr;
      *n = 256;
   }

   strcpy(*lineptr, line); 
   
   return len;
}

int main(int argc, const char* argv[])
{
  int ret           = 0;
  FILE *fp          = NULL;
  char *buffer      = NULL;
  size_t  sz        = 4;
  int count         = 0;
  buffer = (char *) malloc(sz*sizeof(size_t));

  fp = fopen("test.txt", "r");
  if(NULL == fp)
  {
    perror("fopen");
    return -1;
  }

  
  while((ret = my_getline(&buffer, &sz, fp)) > 0)
  {
      printf("ret = %d, buffer: %s\n", ret, buffer);
      count++;
  }

  printf("count=%d\n", count);

  if(buffer != NULL)
  {
    free(buffer);
    buffer = NULL;
  }
  
  return 0;
}


测试结果

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值