Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
1.9 kB
2
Indexable
Never
/****************************************************************
**	Routine: FileMove
**	Returns: TRUE/FALSE success/fail
**	Action : If New is the destination directory we will
**			 attempt to grap the file name from Old and add it to
**			 the destination.
****************************************************************/

int FileMove(
	const char *Old,
	const char *New,
	int Overwrite
)
{
	char FileNameTo[ FILENAME_MAX ];
	stat_type StatBuffer;

	bool TargetFileExists = ( gs_stat( New, &StatBuffer ) == 0 );

	if( TargetFileExists && S_ISDIR( StatBuffer.st_mode ) )
	{
		const char	*Pos;
		// get filename from old and plug it on the of New if Old contains a directory name
		if( ( Pos = strrchr( Old, '/' ) )  // this '/' or that '\' ?
		 || ( Pos = strrchr( Old, '\\' ) ) )
		{
			sprintf( FileNameTo, "%s%s", New, Pos );
			TargetFileExists = ( gs_stat( FileNameTo, &StatBuffer ) == 0 );
		}
		else // if Old is a file name with no directory
			strcpy( FileNameTo, New );
	}
	else
		strcpy( FileNameTo, New );

#ifdef WIN32

	DWORD dwFlags = MOVEFILE_COPY_ALLOWED;

	if( Overwrite )
		dwFlags |= MOVEFILE_REPLACE_EXISTING;

	if( MoveFileEx( Old, FileNameTo, dwFlags ) )
		return TRUE;

	ErrWindows( GetLastError() );
	return ErrMore( "FileMove %s to %s, MoveFileEx failed", Old, New );

#else

	if( !Overwrite && TargetFileExists )
		return Err( ERR_FILE_FAILURE, "FileMove( %s, %s ): destination file already exists", Old, New );

    // Failed to create a hardlink
	if( ( TargetFileExists && remove( New ) != 0 ) || link( Old, New ) != 0 )
	{
		if( FileCopy( Old, FileNameTo ) != 0 )
			return( ErrMore( "FileMove" ) );
	}

	if( remove( Old ) != 0 )
		return Err( ERR_FILE_FAILURE, "FileMove( %s, %s ): could not delete source file", Old, New );

	return TRUE;

#endif /* WIN32 */
}
Leave a Comment