Read and write to a file while keeping lock

前端 未结 3 683
半阙折子戏
半阙折子戏 2020-12-03 22:10

I am making a simple page load counter by storing the current count in a file. This is how I want to do this:

  1. Lock the file (flock)
  2. Read the current c
3条回答
  •  醉梦人生
    2020-12-03 22:39

    Yes, you have to use rewind before ftruncate. Otherwise, the old content of the file is only refilled with zeros.

    The working sequence is:

        fopen
        flock LOCK_EX
        fread filesize
        rewind
        ftruncate 0
        fwrite 
        flock LOCK_UN
        fclose
    

提交回复
热议问题