Path: blob/main/tools/build/cross-build/fgetln_fallback.c
39507 views
/*1* Copyright © 2005 Hector Garcia Alvarez2* Copyright © 2005, 2008-2012 Guillem Jover <[email protected]>3*4* Redistribution and use in source and binary forms, with or without5* modification, are permitted provided that the following conditions6* are met:7* 1. Redistributions of source code must retain the above copyright8* notice, this list of conditions and the following disclaimer.9* 2. Redistributions in binary form must reproduce the above copyright10* notice, this list of conditions and the following disclaimer in the11* documentation and/or other materials provided with the distribution.12* 3. The name of the author may not be used to endorse or promote products13* derived from this software without specific prior written permission.14*15* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,16* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY17* AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL18* THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,19* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,20* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;21* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,22* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR23* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF24* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.25*/2627#include <stdio.h>2829#include <sys/types.h>30#include <string.h>3132#include "local-link.h"3334#define HAVE_GETLINE 135#ifdef HAVE_GETLINE36struct filebuf {37FILE *fp;38char *buf;39size_t len;40};4142#define FILEBUF_POOL_ITEMS 324344static struct filebuf fb_pool[FILEBUF_POOL_ITEMS];45static int fb_pool_cur;4647char *48fgetln(FILE *stream, size_t *len)49{50struct filebuf *fb;51ssize_t nread;5253flockfile(stream);5455/* Try to diminish the possibility of several fgetln() calls being56* used on different streams, by using a pool of buffers per file. */57fb = &fb_pool[fb_pool_cur];58if (fb->fp != stream && fb->fp != NULL) {59fb_pool_cur++;60fb_pool_cur %= FILEBUF_POOL_ITEMS;61fb = &fb_pool[fb_pool_cur];62}63fb->fp = stream;6465nread = getline(&fb->buf, &fb->len, stream);6667funlockfile(stream);6869/* Note: the getdelim/getline API ensures nread != 0. */70if (nread == -1) {71*len = 0;72return NULL;73} else {74*len = (size_t)nread;75return fb->buf;76}77}78libbsd_link_warning(fgetln,79"This function cannot be safely ported, use getline(3) "80"instead, as it is supported by GNU and POSIX.1-2008.")81#else82#error "Function fgetln() needs to be ported."83#endif848586