Put pointer on the second line to write?

0

Writing a text in the file

    $fn = fopen('teste.txt', 'a');
    fwrite($fn, '-meu texto aqui');
    fclose($fn);

Reading the second line of the file

    $fn = "teste.txt";
    $nr_linha = 1;
    $f_contents = file ($fn);
    @$sua_linha = $f_contents [$nr_linha];
    print $sua_linha;

How can I change the first part of the code to write to the second line only? I tried this without success!

    $fn = fopen('teste.txt', 'a');
    @$fc = file ($fn);
    @$fn = $fc [1];
    fwrite($fn, '-alteração na segunda linha');
    fclose($fn);
    
asked by anonymous 28.12.2014 / 17:26

2 answers

2

The first error is to use append mode. You want to write to the file and not add something to the end of the file.

The other thing is that you need to find where the first line ends and start writing soon after. There are several ways to do this. One of them is simpler is to rewrite the first line after reading it. I think you tried to do but actually threw the contents of the first line on top of the file handle, that is, you lost the connection to the file.

In fact there is another problem. The second line may be larger or smaller than the original content, so it would be better to write back everything later.

$fn = fopen('teste.txt', 'w'); //note que isto destrói o conteúdo do arquivo
$fc = file($fn);
$fc[1] = '-alteração na segunda linha';
file_put_contents($fn, $fc);
fclose($fn);

I kept the names of the variables so as not to confuse you but I do not know if they are not exactly the ones that confused you. Giving meaningful names to the variables helps a lot to understand the code.

Finally, do not attempt to access the file concurrently since there is no locking control in this algorithm.

    
28.12.2014 / 18:07
0

Just do it this way:

<?php

//Lê o arquivo
$linhas = explode("\n", file_get_contents("./arquivo.txt"));

//Lê somente o conteúdo da linha [0] do array ou seja linha 1 do texto
$linha_n = $linhas[0];

//Abre o arquivo colocando o ponteiro de escrita no final
$arquivo = fopen('arquivo.txt','r+');
      if ($arquivo) {
while(true) {
$linha = fgets($arquivo);
if ($linha==null) break;

//Busca o conteúdo que vai ser alterado
if(preg_match("/$linha_n/", $linha)) {
$string .= str_replace("$linha_n", "Diego", $linha);
} else {
//Vai colocando tudo numa nova string
$string.= $linha;
}
}
//Move o ponteiro para o início
rewind($arquivo);

//Apaga todo o conteúdo
ftruncate($arquivo, 0);

//Reescreve conteúdo do arquivo
if (!fwrite($arquivo, $string)) die('Não foi possível atualizar');
echo 'Arquivo atualizado';
fclose($arquivo);
}
?>
    
14.02.2017 / 19:52