您好,欢迎来到叨叨游戏网。
搜索
您的当前位置:首页山寨c 标准库中的getline 函数

山寨c 标准库中的getline 函数

来源:叨叨游戏网

要山寨一个函数,只要看两点

下面是函数原型。

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 <stdio.h>
#include <stdlib.h>
#include <string.h>

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;
}


转载于:https://my.oschina.net/guonaihong/blog/278505

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- gamedaodao.net 版权所有 湘ICP备2024080961号-6

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务