delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1997/09/17/20:50:00

Date: Wed, 17 Sep 1997 17:49:02 -0700 (PDT)
Message-Id: <199709180049.RAA25328@adit.ap.net>
Mime-Version: 1.0
To: "David Lenk" <lenkd AT pltpub DOT com>, djgpp AT delorie DOT com
From: Nate Eldredge <eldredge AT ap DOT net>
Subject: Re: please I need help on this!

At 01:18  9/17/1997 GMT, David Lenk wrote:
>This is the of code from a program that I have been trying to write.  I
>need a way of makeing a filename and storing it in a variable so that it
>can be used in a fprintf or fwrite command.  I ask if you could please
>anotate the source if you decide to post any.
>[code deleted]
I think what you want is like this.
--cut--
#include <stdio.h>
#include <stdlib.h>

int main(void) /* main **ALWAYS** returns int, not void */
{
  char filename[L_tmpnam]; /* A buffer to hold a filename */
  FILE *f; /* stream for the file */
  tmpnam(filename); /* Fills filename with a unique filename, TEMP dir. */
  f = fopen(filename,"w");
  if (f == NULL) abort(); /* Could not open file. */
  /* Now do with f whatever you want */
  fprintf(f,"Hello there!\n");
  fclose(f);
  /* You can delete the file if you want */
#ifdef DELETE_FILE
  unlink(filename);
#endif
  return 0;
}
--cut--
The heart is the tmpnam function, which gives you a unique filename. It is
in whatever directory TEMP, TMP or TMPDIR is set to. It has a rather
uncreative name like "dj100000". Read all it's details in the libc docs
under `tmpnam'.
A related function is `tmpfile', which picks a filename, opens it, and gives
you the FILE pointer. It automatically deletes the file when the program exits.

Hope this helps. If not, tell me.

Nate Eldredge
eldredge AT ap DOT net



- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019