What drupal function do I use to rename files when saving nodes programatically? Normally when saving a node with the content type form, uploading a file will automatically rename it if the file name is already in the database.

I am creating nodes programatically. Everything works fine, except if the file name is in the database it fails as this is, of course, a unique field.

What function does Drupal use to check if the name already exists and chanages it accordingly? I could write one, but as drupal already seems to handle this perfectly, I dont see a reason to reinvent the wheel. Here is my code for the file saves.

$file = new stdClass();
$file-&gt;filename = basename($local_path);
$file-&gt;filepath = $local_path;
$file-&gt;uri = $local_path;
$file-&gt;filemime = $mime;
$file-&gt;filesize = filesize($local_path);

$file-&gt;uid = $uid; 
$file-&gt;status = FILE_STATUS_PERMANENT;
file_save($file);

$images[] = array(
'fid' =&gt; $file-&gt;fid,
'alt' =&gt; $page_data['title'],
'title' =&gt; $page_data['title']
);
Drupal uses the file_create_filename() function to do that, you can call it like this:

$basename = drupal_basename($local_path);
$directory = drupal_dirname($local_path);
$local_path = file_create_filename($basename, $directory);

$file = new stdClass();
$file-&gt;filename = drupal_basename($local_path);
$file-&gt;filepath = $local_path;
// etc...