Skip to content

Instantly share code, notes, and snippets.

@RSully
Created January 12, 2016 02:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RSully/8090f76ae88938f6f29c to your computer and use it in GitHub Desktop.
Save RSully/8090f76ae88938f6f29c to your computer and use it in GitHub Desktop.
Keep trying to copy a file until success.
<?php
$path = '/Volumes/drive/path.dat';
$write_to = '/tmp/output.dat';
$fh_out = fopen($write_to, 'w+');
clearstatcache();
while (!file_exists($path)) {
sleep(1);
}
$stat = stat($path);
$size = $stat['size'];
$seek = 0;
print_r($stat);
while ($seek < $size) {
sleep(1);
$fh = fopen($path, 'r');
if ($fh === false) {
printf("failed to open file\n");
continue;
}
printf("opened file\n");
$seeked = fseek($fh, $seek, SEEK_SET);
if ($seeked === -1) {
printf("failed to seek\n");
@fclose($fh);
continue;
}
$block = 1024*4;
while (true) {
$data = fread($fh, $block);
if ($data === false || empty($data)) {
printf("read failed %d %d\n", $seek, $block);
@fclose($fh);
continue 2;
}
$res = fwrite($fh_out, $data);
if ($res === false) {
printf("failed to write?\n");
continue 2;
}
unset($data);
$data = null;
$seek += $block;
}
}
fclose($fh_out);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment