/*
* 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;
}
getline函数使用
最新推荐文章于 2023-08-20 10:39:07 发布