mailing list of musl libc
 help / color / mirror / code / Atom feed
* portable fgetln
@ 2012-08-12  0:24 Rich Felker
  0 siblings, 0 replies; only message in thread
From: Rich Felker @ 2012-08-12  0:24 UTC (permalink / raw)
  To: musl

[-- Attachment #1: Type: text/plain, Size: 670 bytes --]

Hi all,

Based on a discussion on #musl about the merits of fgetln as an
efficient (probably optimal) way to do line-based stdio processing if
the implementation is good, I got to wondering if it's viable to use
the interface in programs intended to be portable, i.e. if it could be
written portably for use on any stdio implementation or at least any
POSIX one. Here's the result -- a sample portable implementation that
keeps a separate buffer for each fd, or for each FILE* when the stream
lacks an associated fd. It has some limitations, but it seems to meet
the interface contract and avoids using a single static buffer that
would render if non-thread-safe.

Rich

[-- Attachment #2: portable_fgetln.c --]
[-- Type: text/plain, Size: 931 bytes --]

#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>

struct entry
{
	struct entry *next;
	int fd;
	FILE *f;
	char *buf;
};

struct entry *table[64];

#define K (sizeof table / sizeof table[0])

pthread_rwlock_t lock = PTHREAD_RWLOCK_INITIALIZER;

char *fgetln(FILE *f, size_t *l)
{
	int fd, h;
	struct entry *p;
	ssize_t cnt;
	char *ret = 0;

	flockfile(f);
	fd = fileno(f);
	h = fd % K;

	pthread_rwlock_rdlock(&lock);
	for (p=table[h]; p && (p->fd!=fd || (fd<0 && p->f!=f)); p=p->next);
	if (!p) {
		if (!(p = calloc(sizeof *p, 1))) {
			pthread_rwlock_unlock(&lock);
			funlockfile(f);
			return 0;
		}
		p->fd = fd;
		p->f = f;
		pthread_rwlock_unlock(&lock);
		pthread_rwlock_wrlock(&lock);
		p->next = table[h];
		table[h] = p;
	}
	pthread_rwlock_unlock(&lock);
	cnt = getline(&p->buf, (size_t[]){0}, f);
	if (cnt >= 0) {
		*l = cnt;
		ret = p->buf;
	}
	funlockfile(f);
	return ret;
}

^ permalink raw reply	[flat|nested] only message in thread

only message in thread, other threads:[~2012-08-12  0:24 UTC | newest]

Thread overview: (only message) (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2012-08-12  0:24 portable fgetln Rich Felker

Code repositories for project(s) associated with this public inbox

	https://git.vuxu.org/mirror/musl/

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).