We help IT Professionals succeed at work.

How do you implement a "copy algorithm" (like the one in Windows Explorer)?

ttanyag
ttanyag asked
on
How do you implement a "copy algorithm" (like the one in Windows Explorer)?

ex.

  given= File1 is the original filename

  1. copy File1
     result:
       - File1
       - 'Copy of '+File1
  2. copy 'Copy of '+File1
     result:
       - File1
       - 'Copy of '+File1
       - 'Copy of '+Copy of File1
  3. copy File1
     result:
       - File1
       - 'Copy of '+File1
       - 'Copy of '+Copy of File1
       - 'Copy (2) of '+File1
  4. copy File1
     result:
       - File1
       - 'Copy of '+File1
       - 'Copy of '+Copy of File1
       - 'Copy (2) of '+File1
       - 'Copy (3) of '+File1
  5. copy 'Copy (2) of '+File1
     result:
       - File1
       - 'Copy of '+File1
       - 'Copy of '+Copy of File1
       - 'Copy (2) of '+File1
       - 'Copy (3) of '+File1
       - 'Copy (4) of '+File1

  I just need a function that will give me the appropriate new filename of the copied file.

  Thanks :)
       
Comment
Watch Question

Commented:
I'm gonna implement the Windows 2000 algorithm: All it does
is prepend the existing filename with 'Copy of', even if the filename already begins with 'Copy of'. Only if you paste the same file again, will you get 'Copy (2) of'....
Examples:
1. You copy 'File1.txt', you get 'Copy of File1.txt'
2. You copy 'File1.txt' AGAIN, you get 'Copy (2) of File1.txt'
3. You copy 'File1.txt' AGAIN, you get 'Copy (3) of File1.txt'
4. You copy 'Copy of File1.txt', you get 'Copy of Copy of File1.txt'
5. You copy 'Copy of File1.txt' AGAIN, you get 'Copy (2) of Copy of File1.txt'



//Generates a new filename for a copy in the same folder
//SourceFile must be a fully qualified path & filename
function GetCopyFileName(const SourceFile: string): string;
const
  COPY_PREFIX = 'Copy ';
  OF_PREFIX = 'of ';
  NUM_PREFIX = '(%d) ';
var
  path, fname, newfile: string;
  copynum: integer;
begin
  Result := '';
  path := ExtractFilePath(SourceFile);
  if path = '' then exit;
  fname := ExtractFileName(SourceFile);
  if fname = '' then exit;
  copynum := 1;
  newfile := path + COPY_PREFIX + OF_PREFIX + fname;
  while FileExists(newfile) do
  begin
    inc(copynum);
    newfile := path + COPY_PREFIX + Format(NUM_PREFIX,[copynum]) + OF_PREFIX + fname;
  end;
  Result := newfile;
end;

Author

Commented:
thank you very much!

Explore More ContentExplore courses, solutions, and other research materials related to this topic.