頭檔案:
#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 binsize 4len 120line bootsize 5len 120line devsize 4len 120