头文件:
#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