学习自李慧琴老师

前面所了解的函数没有一个可以帮助我们完整的获取一行数据
现在有了 :getline()
NAME
getline, getdelim - delimited string input
SYNOPSIS
#include <stdio.h>
ssize_t getline(char **lineptr, size_t *n, FILE *stream);
ssize_t getdelim(char **lineptr, size_t *n, int delim, FILE *stream);
getline() reads an entire line from stream, storing the address of the buffer containing the text into *lineptr. The buffer is null-terminated and includes the newline character, if one was found.
从 stream流中读取完整的一行内容。并将读取到一行字符的缓冲区地址存储到 指针变量 lineptr。
CONFORMING TO
Both getline() and getdelim() were originally GNU extensions. They were standardized in POSIX.1-2008.
/*
char **lineptr : 读出来的一行字符的buffer的地址
size_t *n,该空间的大小值的地址
目标文件
*/
ssize_t getline(char **lineptr, size_t *n, FILE *stream);
该函数内部机制是这样的。首先我们自己定义一个字符指针,该指针指向的空间用于存放我们读取出来的当前一行的字符,但是我们只提供字符指针,至于该字符指针指向哪一块内存空间,指向多大的内存空间 都不是我们决定的,是函数内部帮我们实现的。我们只负责传递如下3个参数:
字符指针,指向存储目标文件目标行的字符的空间
整型值地址,用于记录 为我们申请的空间有多大,我们可以直接查看该值。
目标文件
经过试验,发现 如果靠前几行每一行的字符数不足120个字符,那么每一行申请的空间就是120,如果大于120,那么就申请240。。。。
猜测过程
getline 是以行为单位的操作,返回是每一行的数据,假如目标文件第一行只有50和字符,那么在函数内部,就会将我们的字符指针指向一个大小为120个字节的堆空间,将读来的数据存储在该空间,如果目标文件中某一行的数据比较大,比操作上一行数据时候所申请的空间容量大,那么该函数就会将我们的字符指针指向的空间进行扩容,以存储新的一行的数据,那么操作完该行之后,下一行的数据默认以上一行所用的空间为基础继续操作。
返回值
On success, getline() and getdelim() return the number of characters read, including the delimiter character, but not including the terminating null byte (’\0’). This value can be used to handle embedded null bytes in the line read.
getline 使用
#include<stdio.h>
#include<stdlib.h>
#include <errno.h>
#include <string.h>
int main(int argc,char** argv)
//int main(int argc,char *argv[])
{
FILE *fp;
char *linebuf = NULL;
size_t linesize = 0;
if(argc < 2)
{
fprintf(stderr,"Usage:%s <src_file>\n",argv[1]);
exit(1);
}
fp = fopen(argv[1],"r");
if(fp == NULL)
{
fprintf(stderr,"fopen() failed! errno = %d\n",errno);
exit(1);
}
while(1)
{
if(getline(&linebuf,&linesize,fp) < 0)
break;
printf("%d\n",strlen(linebuf));
printf("%d\n",linesize);
}
fclose(fp);
exit(0);
}
mhr@ubuntu:~/work/linux/stdio/gerline$ ./a.out test
18
120
19
120
18
120
19
120
11
120
1
120
mhr@ubuntu:~/work/linux/stdio/gerline$
本文详细介绍了如何使用getline()函数从文件中读取完整的一行数据,并解析了其内部机制,包括如何动态调整缓冲区大小以适应不同长度的行。
908

被折叠的 条评论
为什么被折叠?



