I've been unable to find a PHP function that will convert eol in files. This is what I have so far. It works, no errors.
Your educated opinions, thoughts, improvements, potential bugs and suggestions are welcome.
/*
$file_name - full/path/to/file.name
$eol - wanted end of line: "\n", "\r", "\r\n"
from "\n" to "\r" || "\r\n"
from "\r\n" to "\r" || "\n"
from "\r" to "\n"
$len - buffer size
return true on success or false on fail
*/
function file_eol($file, $eol, $len=8192) {
$ok = FALSE;
$extension = '.my_temp';
$hread = FALSE;
if (is_string($file)) $hread = fopen($file, 'rb');
if ($hread === FALSE) e("Bad file in file_eol(): $file");
if (!is_resource($hread) || get_resource_type($hread) !== 'stream') e("Bad hread in file_eol(): $hread");
$hsave = fopen($file.$extension, 'wb');
if ($hsave === FALSE) e("Bad hsave file in file_eol(): $file.my_temp");
switch ($eol) {
case "\n": $order = array("\r\n", "\r"); // from "\r\n" || "\r" -> "\n"
break;
case "\r": $order = array("\r\n", "\n"); // from "\r\n" || "\n" -> "\r"
break;
case "\r\n": $order = array("\n", "\r\r\n"); // from "\n" -> "\r\n"
break;
default:
e("Bad eol in file_eol(): $eol");
}
while (($str = fread($hread, $len)) && $str !== FALSE) { // error or eof
$new = str_replace($order, $eol, $str);
// if (is_string($new)) $ok = fwrite($hsave, $new); // this ???
if ($new !== '') $ok = fwrite($hsave, $new);
if ($ok === FALSE) break; // or e("Error writing file: $file$extension");
}
$ok = $ok === FALSE ? FALSE : TRUE; // ok could be valid 0bytes
$ok = $ok && ((bool)$str || feof($hread)); // check if fread and feof failed
$ok = $ok && fclose($hread) && fclose($hsave); // ALWAYS check for fclose!
if ($ok) $ok = rename($file.$extension, $file); // overwrite $file, and delete $file.$extension
// else leave both files for later inspection
return $ok;
}
P.S. copy/paste should work if you create error handler function e()
that will take string inputs or just change e()
to trigger_error
or whatever you want.
Edit:
Must include feof()
$ok = $ok && ((bool)$str || feof($hread)); // check if fread and feof failed