Create a managed file

 * Create a directory, add a managed file,
 * and create url from the new file object.
function _demo_file_managed() {
  $filedir = 'public://demo';
  // Create a demo directory in the public dir.
  // file_prepare_directory checks, creates and sets permissions on a directory path.
  $prepared = file_prepare_directory($filedir, FILE_MODIFY_PERMISSIONS | FILE_CREATE_DIRECTORY);
  dpm('Directory prepared => ' . $prepared);
  // Save a managed file.
  // Managed means a database entry is created in the file_managed table.
  $file = file_save_data('This is a demo text.', $filedir . '/demo.txt');
  // Create an url from a filepath.
  $url = file_create_url($file->uri);