Home > Software engineering >  Read and write file with one fopen
Read and write file with one fopen

Time:10-20

With the following code I would like to read a number from file, increase it, an write back.

      $DATdatei = fopen("$dir$datFile", "rw ");       
      $count = (int) fgets($DATdatei, 5000);     
      $count  ;
      fwrite($DATdatei, $count);
      fclose($DATdatei);

But on writing back the number will be appended to the old number. I will get 1, then 12, and then 1213 ... How to avoid it.

CodePudding user response:

After the fgets(), the file pointer will remain the the end of the file.

fwrite() will write it's data at that pointer.

Use a rewind() call to set the file pointer to the beginning, to overwrite the content:

rewind — Rewind the position of a file pointer

<?php

      $DATdatei = fopen("$dir$datFile", "rw ");
      $count = (int) fgets($DATdatei);
      $count  ;
      
      rewind($DATdatei);
      fwrite($DATdatei, $count);
      fclose($DATdatei);
  •  Tags:  
  • php
  • Related