lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


gcc complains about tmpnam when using the -Werror option, I propose this code to rectify that:
typedef unsigned int lua_uint;
size_t u2a( char *str, size_t size, lua_uint val, lua_uint base, lua_uint small ) {
static const char bstr[] = "0123456789ABCDEF";
static const char sstr[] = "0123456789abcdef";
static const size_t min = (sizeof(int) * CHAR_BIT);
    const char *s = small ? sstr : bstr;
    size_t i = 0;
    if ( !str || !size || base < 2 || base > strlen(s) ) return 0;
    --size;
    if ( size < min ) {
        memset( str, 0, size );
        return 0;
    }
    while ( val > 0u ) {
        str[i++] = s[val % base];
        val /= base;
    }
    str[i] = 0;
    return i;
}
/* Avoids unistd.h, can expect sys/stat.h on all supported systems */
#include <sys/stat.h>
size_t tmpname( char *str, size_t size ) {
    size_t i;
    struct stat m = {0};
    if ( u2a( str, --size, 0, 2, 0 ) == 0 ) return 0;
    str[0] = '_';
    ++str;
    do {
        i = u2a( str, size, rand(), 16, 1 );
    } while ( stat(str,&m) == 1 );
    return i;
}

static int os_tmpname (lua_State *L) {
  char buff[LUA_TMPNAMBUFSIZE];
  if ( tmpname(buff, LUA_TMPNAMBUFSIZE) == 0 )
    return luaL_error(L, "unable to generate a unique filename");
  lua_pushstring(L, buff);
  return 1;
}
Feel free to modify