Add file while inserting post

You can attach images to a post from URI via the media_sideload_image function:

$post = array(); // your post data
$post_id = wp_insert_post( $post );
$url = "http://s.wordpress.org/style/images/wp3-logo.png";
$desc = "The WordPress Logo";
$image = media_sideload_image( $url, $post_id, $desc );