getline函数-linux

头文件:

#include <stdio.h>

函数:

ssize_t getline(char **lineptr, size_t *n, FILE *stream);


eg:

ssize_t size;//存放 当前行 的长度(包括“\n”)

char * line = NULL;//存放 当前行 的字符串

size_t len;//文件总长度

FILE *fp;

size = getline( &line, &len, fp );


[

注意;

最后需要判断 line 是否为空指针,如果不是需要释放

]


一、解释[ man getline ]

#include <stdio.h>

#include <stdlib.h>
int main(void)
{

FILE * fp;

char * line = NULL;

size_t len = 0;

ssize_t read;


fp = fopen("/etc/motd", "r");


if (fp == NULL)

exit(EXIT_FAILURE);


while ((read = getline(&line, &len, fp)) != -1) 

{

printf("Retrieved line of length %zu :\n", read);
printf("%s", line);

}


if (line)

free(line);


return EXIT_SUCCESS;

}


二、分析:

1、程序:

#include <stdio.h>

#include <stdlib.h>

int main(void)

{

        FILE * fd;

        ssize_t size;//存放 当前行 的长度(包括“\n”)

        size_t len = 0;//文件总长度

        char * line = NULL;//存放 当前行 的字符串


        system( "ls / >>log" );

        fd = fopen( "log", "r" );


        size = getline( &line, &len, fd);

        printf( "line %s\n", line );

        printf( "size %d\n", size );

        printf( "len %d\n", len );


        size = getline( &line, &len, fd);

        printf( "line %s\n", line );

        printf( "size %d\n", size );

        printf( "len %d\n", len );


        size = getline( &line, &len, fd);

        printf( "line %s\n", line );

        printf( "size %d\n", size );

        printf( "len %d\n", len );


        if(line)[注释: 释放 line]

                free(line);

        return 0;

}


2、结果:

line bin

size 4

len 120


line boot

size 5

len 120


line dev

size 4

len 120




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值