tmpnam.c 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * tmpnam for uClibc
  4. *
  5. * Copyright (C) 2000 by David Whedon <dwhedon@gordian.com>
  6. *
  7. * This program is free software; you can redistribute it and/or modify it
  8. * under the terms of the GNU Library General Public License as published by
  9. * the Free Software Foundation; either version 2 of the License, or (at your
  10. * option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful, but WITHOUT
  13. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  14. * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License
  15. * for more details.
  16. *
  17. * You should have received a copy of the GNU Library General Public License
  18. * along with this program; if not, write to the Free Software Foundation,
  19. * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  20. *
  21. * Modified by Erik Andersen <anderse@debian.org> to be reentrant for
  22. * the case when S != NULL...
  23. */
  24. #include <stdio.h>
  25. #include <string.h>
  26. #include <unistd.h>
  27. #include <sys/types.h>
  28. #include <sys/stat.h>
  29. static char tmpnam_buffer[L_tmpnam];
  30. /* Generate a unique filename in /tmp */
  31. char * tmpnam (char *s)
  32. {
  33. int num __attribute__ ((unused)); /* UNINITIALIZED, so we get whatever crap
  34. happens to be in memory, producing (in theory)
  35. pseudo-random tmpname results... */
  36. int n2;
  37. char buf[L_tmpnam], *ptr;
  38. struct stat statbuf;
  39. unsigned char l, i;
  40. ptr=s ? s : buf;
  41. l = snprintf(ptr, L_tmpnam, "%s/tmp.", P_tmpdir);
  42. again:
  43. n2 = num;
  44. for (i = l ; i < l + 6; i++) {
  45. ptr[i] = '0' + n2 % 10;
  46. n2 /= 10;
  47. }
  48. if (stat (ptr, &statbuf) == 0){
  49. num++;
  50. goto again;
  51. }
  52. if (s == NULL)
  53. return (char *) memcpy (tmpnam_buffer, ptr, L_tmpnam);
  54. return ptr;
  55. }