diff --git a/src/util.cpp b/src/util.cpp index bf630ddc..efb13933 100644 --- a/src/util.cpp +++ b/src/util.cpp @@ -325,13 +325,28 @@ char *center_string(const char *name, size_t s) bool file_exists(const char *name) { - int fd; + int fd, r; + struct stat st; + /* return true if we can open it */ fd = open(name,O_RDONLY); - if (fd < 0) - return 0; - (void) close(fd); - return 1; + if (fd >= 0) + { + (void) close(fd); + return true; + } + + /* return true if we can stat it */ + memset(&st, 0, sizeof(st)); +#if defined(HAVE_LSTAT) + r = lstat(name,&st); +#else + r = stat(name,&st); +#endif + if (r != -1) + return true; + + return false; } @@ -363,9 +378,10 @@ bool maketempname(char *ofilename, const char *ifilename, } -void makebakname(char *ofilename, const char *ifilename) +bool makebakname(char *ofilename, const char *ifilename, bool force) { char *ofext = NULL, *ofname; + int ofile; strcpy(ofilename, ifilename); for (ofname = fn_basename(ofilename); *ofname; ofname++) @@ -374,11 +390,24 @@ void makebakname(char *ofilename, const char *ifilename) ofext = ofname; } if (ofext == NULL) - strcat(ofilename, ".~"); + { + ofext = ofilename + strlen(ofilename); + strcpy(ofext, ".~"); + } else if (strlen(ofext) < 1 + 3) strcat(ofilename, "~"); else ofext[strlen(ofext)-1] = '~'; + if (!force) + return true; + if (file_exists(ofilename)) + for (ofile = 0; ofile < 999; ofile++) + { + sprintf(ofext, ".%03d", ofile); + if (!file_exists(ofilename)) + return true; + } + return false; } diff --git a/src/util.h b/src/util.h index 194e2943..631869ec 100644 --- a/src/util.h +++ b/src/util.h @@ -43,8 +43,8 @@ bool fn_has_ext(const char *name, const char *ext); bool file_exists(const char *name); bool maketempname(char *ofilename, const char *ifilename, - const char *ext, bool force); -void makebakname(char *ofilename, const char *ifilename); + const char *ext, bool force=true); +bool makebakname(char *ofilename, const char *ifilename, bool force=true); bool isafile(int fd); unsigned get_ratio(unsigned long packedsize, unsigned long size, diff --git a/src/work.cpp b/src/work.cpp index a3bd2301..3f5ea8d1 100644 --- a/src/work.cpp +++ b/src/work.cpp @@ -99,7 +99,7 @@ void do_one_file(const char *iname, char *oname) if (opt->output_name) strcpy(tname,opt->output_name); else - maketempname(tname,iname,".upx",1); + maketempname(tname,iname,".upx"); if (opt->force >= 2) { #if defined(HAVE_CHMOD) @@ -177,8 +177,6 @@ void do_one_file(const char *iname, char *oname) // make backup char bakname[PATH_MAX+1]; makebakname(bakname,iname); - if (file_exists(bakname)) - maketempname(bakname,iname,".000",1); File::rename(iname,bakname); } File::rename(oname,iname);