On Sunday 06 August 2006 9:57 pm, Carl William Spitzer IV wrote:
its not a tmp file program its a renaming program so mkstemp does not
solve the problem.
yes it does. Your program renames the program with a unique name. mkstemp()
creates a file with a unique name. All you need to do is remove the file
created by mkstemp. I had some old code I was porting with the old Unix
tempnam() deprecated functions, so I updated my code. This program should
do pretty much what yours is supposed to do. Note that the file name could
be a full path, a relative path (foo/bar/fubar.c) or simply a filename.
#include
#include
#include
#include
int main(int argc, char **argv)
{
char newname[256];
char *oldname = argv[1];
char *ext;
char *relp;
char thispath[256];
int fd, rc;
char cmd[128];
if (argc != 2) {
fprintf(stderr, "Usage maketemp <filename>\n");
exit(-1);
}
ext = strrchr(oldname, '.');
if (oldname[0] == '/') { /* we have full path */
strcpy(thispath, oldname); /* copy path */
relp = strrchr(thispath, '/'); /* locate last '/' */
relp[0] = '\0'; /* truncate */
} else {
/* We have a relative path or bare filename use current directory */
if (getcwd(thispath, sizeof(thispath)) == NULL) {
perror("getcwd");
return -1;
}
if (strchr(oldname, '/')) {
strcat(thispath, "/"); /* Need this when oldname has a '/' */
strcat(thispath, oldname);
relp = strrchr(thispath, '/'); /* locate last '/' */
relp[0] = '\0'; /* truncate */
}
}
/* at this point, thispath contains the directory portion or current
directory */
sprintf(newname, "%s/XXXXXX", thispath);
printf("Creating file:%s\n", newname);
fd = mkstemp(newname);
if (fd < 0) {
perror("mkstemp");
exit(-1);
}
sprintf(cmd, "ls -l \"%s\"", newname);
system(cmd);
close(fd);
unlink(newname); /* remove the file created by mkstemp */
system(cmd); /* just do an ls -l */
if (ext != NULL) {
strcat(newname, ext); /* Add extension */
}
printf("renaming %s to :%s\n", oldname, newname);
sprintf(cmd, "ls -l \"%s\"", newname);
if (rename(oldname, newname) == -1) {
perror("rename");
return -1;
}
system(cmd); /* just do an ls -l */
return 0;
}
--
Jerry Feldman
Boston Linux and Unix user group
http://www.blu.org PGP key id:C5061EA9
PGP Key fingerprint:053C 73EC 3AC1 5C44 3E14 9245 FB00 3ED5 C506 1EA9