Home  >  Q&A  >  body text

php - 关于fwrite和fread操作同一个文件

$fp = fopen("./log", "a+");
fwrite($fp,"helloworld");
rewind($fp);
var_dump( fread($fp, 10) );
fclose($fp);

执行这段代码,文件里被写入了两个helloworld,这是为什么?
还有就是这段话怎么理解:

Update mode permits reading and writing the same file; fflush or a
file-positioning function must be called between a read and a write or
vice versa. If the mode includes b after the initial letter, as in
"rb" or "w+b", that indicates a binary file. Filenames are limited to
FILENAME_MAX characters. At most FOPEN_MAX files may be open at once.

怪我咯怪我咯2685 days ago1777

reply all(3)I'll reply

  • 巴扎黑

    巴扎黑2017-05-16 12:04:35

    The

    fopen的第二个参数为模式, 有r, w, b, a等模式, 其中a表示append, 也就是附加的意思, 打开时不会清空文件(把EOF指向0), 而是把文件指针指向文件末尾. 所以这个时候如果直接写的话不会覆盖原有的内容. 通过rewind function points the file pointer to the starting point. Writing at this time will overwrite the original content. For example:

    $fp = open('./log.txt', 'w+');
    fwrite($fp, '12345');
    fclose($fp); // 此时文件的内容一定是'12345', 无论在之前是什么
    $fp = open('./log.txt', 'a+');
    fwrite($fp, '67890');  // 此时文件内容为'1234567890'
    rewind($fp);
    fwrite($fp, 'abcde'); // 此时文件内容为'abcde67890'
    fclose($fp);

    reply
    0
  • 大家讲道理

    大家讲道理2017-05-16 12:04:35

    There are two reasons: you are in append mode and have not cleared the last helloworld, so the last time and the current time are both there

    reply
    0
  • 滿天的星座

    滿天的星座2017-05-16 12:04:35

    fopen("./log", "a+"); This sentence means to open a readable and writable file in an appended manner. If the file exists, the original content will be retained, and the data will be appended to the end of the file.

    At this time, the $fp file pointer points to the end of the file for operation
    fwrite($fp, '12345');

    At this time, if fread($fp, 10) is printed directly, it will be an empty string. This is because the $fp file pointer points to the end of the file. If the length is specified, reading and printing backwards will definitely be empty.
    And if you add rewind($fp); to rewind the position of the file pointer, you will find that the $fp pointer points to the beginning of the file, and printing fread($fp, 10) will result.

    But when you open your log, it is appended to the end of the file every time.

    reply
    0
  • Cancelreply