hamburger
hamburger

Reputation: 1415

Read and write file with one fopen

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.

Upvotes: 0

Views: 51

Answers (1)

0stone0
0stone0

Reputation: 43884

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);

Upvotes: 1

Related Questions