diff --git a/programs/fileio.c b/programs/fileio.c index 8a571511..ffa43ab2 100644 --- a/programs/fileio.c +++ b/programs/fileio.c @@ -515,28 +515,10 @@ static FILE* FIO_openDstFile(FIO_prefs_t* const prefs, const char* srcFileName, return stdout; } - /* ensure dst is not the same file as src */ - if (srcFileName != NULL) { -#ifdef _MSC_VER - /* note : Visual does not support file identification by inode. - * The following work-around is limited to detecting exact name repetition only, - * aka `filename` is considered different from `subdir/../filename` */ - if (!strcmp(srcFileName, dstFileName)) { - DISPLAYLEVEL(1, "zstd: Refusing to open a output file which will overwrite the input file \n"); - return NULL; - } -#else - stat_t srcStat; - stat_t dstStat; - if (UTIL_getFileStat(srcFileName, &srcStat) - && UTIL_getFileStat(dstFileName, &dstStat)) { - if (srcStat.st_dev == dstStat.st_dev - && srcStat.st_ino == dstStat.st_ino) { - DISPLAYLEVEL(1, "zstd: Refusing to open a output file which will overwrite the input file \n"); - return NULL; - } - } -#endif + /* check if src file is the same as dst */ + if (srcFileName != NULL && UTIL_isSameFile(srcFileName, dstFileName)) { + DISPLAYLEVEL(1, "zstd: Refusing to open an output file which will overwrite the input file \n"); + return NULL; } if (prefs->sparseFileSupport == 1) { diff --git a/programs/util.c b/programs/util.c index d6466063..622e5025 100644 --- a/programs/util.c +++ b/programs/util.c @@ -87,6 +87,23 @@ U32 UTIL_isDirectory(const char* infilename) return 0; } +int UTIL_isSameFile(const char* file1, const char* file2) +{ +#if defined(_MSC_VER) + /* note : Visual does not support file identification by inode. + * The following work-around is limited to detecting exact name repetition only, + * aka `filename` is considered different from `subdir/../filename` */ + return !strcmp(file1, file2); +#else + stat_t file1Stat; + stat_t file2Stat; + return UTIL_getFileStat(file1, &file1Stat) + && UTIL_getFileStat(file2, &file2Stat) + && (file1Stat.st_dev == file2Stat.st_dev) + && (file1Stat.st_ino == file2Stat.st_ino); +#endif +} + U32 UTIL_isLink(const char* infilename) { /* macro guards, as defined in : https://linux.die.net/man/2/lstat */ diff --git a/programs/util.h b/programs/util.h index f78bcbe1..eee7ebfc 100644 --- a/programs/util.h +++ b/programs/util.h @@ -174,6 +174,7 @@ int UTIL_isRegularFile(const char* infilename); int UTIL_setFileStat(const char* filename, stat_t* statbuf); U32 UTIL_isDirectory(const char* infilename); int UTIL_getFileStat(const char* infilename, stat_t* statbuf); +int UTIL_isSameFile(const char* file1, const char* file2); U32 UTIL_isLink(const char* infilename); #define UTIL_FILESIZE_UNKNOWN ((U64)(-1))