Re: [PATCH 13/15] tools/nolibc: add fopen()

From: Willy Tarreau
Date: Sat Apr 26 2025 - 06:58:57 EST


On Wed, Apr 23, 2025 at 05:01:43PM +0200, Thomas Weißschuh wrote:
> +static __attribute__((unused))
> +FILE *fopen(const char *pathname, const char *mode)
> +{
> + int flags, fd;
> +
> + if (!strcmp(mode, "r"))
> + flags = O_RDONLY;
> + else if (!strcmp(mode, "w"))
> + flags = O_WRONLY | O_CREAT | O_TRUNC;
> + else if (!strcmp(mode, "a"))
> + flags = O_WRONLY | O_CREAT | O_APPEND;
> + else if (!strcmp(mode, "r+"))
> + flags = O_RDWR;
> + else if (!strcmp(mode, "w+"))
> + flags = O_RDWR | O_CREAT | O_TRUNC;
> + else if (!strcmp(mode, "a+"))
> + flags = O_RDWR | O_CREAT | O_APPEND;
> + else {
> + SET_ERRNO(EINVAL);
> + return NULL;
> + }

I'm concerned by the size of the function due to the repeated strcmp()
calls (also I find strcmp()==0 more readable that !strcmp() which I tend
to read as "not string compares").

I have not tried the code below but I think it could cover it in a maybe
lighter way:

switch (*mode) {
case 'r": flags = O_RDONLY; break;
case 'w': flags = O_WRONLY | O_CREAT | O_TRUNC; break;
case 'a': flags = O_WRONLY | O_CREAT | O_APPEND; break;
default : SET_ERRNO(EINVAL); return NULL;
}

if (mode[1] == '+')
flags = (flags & ~(O_RDONLY|O_WRONLY)) | O_RDWR;

I think it does the same but should be significantly lighter.

Willy