要山寨一个函数,只要看两点
原版函数的形参。
原函数的返回值。
下面是函数原型。
ssize_t getline(char **lineptr, size_t *n, FILE *stream);
函数返回值。
RETURN VALUE
On success, getline() and getdelim() return the number of characters read, including the delimiter character, but not including the terminating null byte. This value can be used to handle embedded null bytes in the line read.
Both functions return -1 on failure to read a line (including end-of-file condition).
下面是山寨getline 实现代码。
#include
#include
#include
ssize_t ho_getline(char **buf, size_t *n, FILE *fp) {
char c;
int needed = 0;
int maxlen = *n;
char *buf_ptr = *buf;
if (buf_ptr == NULL || maxlen == 0) {
maxlen = 128;
if ((buf_ptr = malloc(maxlen)) == NULL)
return -1;
}
do {
c = fgetc(fp);
buf_ptr[needed++] = c;
if (needed >= maxlen) {
*buf = buf_ptr;
buf_ptr = realloc(buf_ptr, maxlen *= 2);
if (buf_ptr == NULL) {
(*buf)[needed - 1] = '\0';
return -1;
}
}
if (c == EOF)
return -1;
} while (c != '\n');
buf_ptr[needed] = '\0';
*buf = buf_ptr;
*n = maxlen;
return needed;
}
测试代码:
void test_main(const char *fname) {
FILE *fp;
char *line = NULL;
size_t len = 0;
ssize_t read;
fp = fopen(fname, "r");
if (fp == NULL)
exit(EXIT_FAILURE);
while ((read = ho_getline(&line, &len, fp)) != -1) {
printf("Retrieved line of length %zu :\n", read);
printf("%s", line);
}
fclose(fp);
free(line);
}
int main(void) {
test_main("/etc/motd");
return 0;
}