Pregunta

¿Por qué es mi script PHP colgando?

$path = tempnam(sys_get_temp_dir(), '').'.txt';
$fileInfo = new \SplFileInfo($path);
$fileObject = $fileInfo->openFile('a');
$fileObject->fwrite("test line\n");
var_dump(file_exists($path));          // bool(true)
var_dump(file_get_contents($path));    // string(10) "test line
                                       // "
var_dump(iterator_count($fileObject)); // Hangs on this

Si puedo borrar la última línea (iterator_count(...) y reemplazarlo con este:

$i = 0;
$fileObject->rewind();
while (!$fileObject->eof()) {
    var_dump($fileObject->eof());
    var_dump($i++);
    $fileObject->next();
}
// Output:
// bool(false)
// int(0)
// bool(false)
// int(1)
// bool(false)
// int(2)
// bool(false)
// int(3)
// bool(false)
// int(4)
// ...

El $fileObject->eof() siempre devuelve false, así que conseguir un bucle infinito.

¿Por qué suceden estas cosas?Necesito obtener un número de línea.

¿Fue útil?

Solución

Por lo que veo en tu código, se abre el archivo con el modo de a en esta línea:

$fileObject = $fileInfo->openFile('a');

Cuando haces eso, su escritura sólo:

$fileObject->eof() necesita leer el archivo, usted debe abrir el archivo con a+ para permitir la lectura/escritura:

$fileObject = $fileInfo->openFile('a+');

Ps:ya sea con a o a+, el puntero se va al final del archivo.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top