php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #80088 c+ open mode messes up file on fwrite()
Submitted: 2020-09-10 22:19 UTC Modified: 2020-09-10 22:28 UTC
From: smitty7523 at yahoo dot com Assigned:
Status: Not a bug Package: Filesystem function related
PHP Version: 7.4.10 OS: Linux Manjaro
Private report: No CVE-ID: None
View Add Comment Developer Edit
Anyone can comment on a bug. Have a simpler test case? Does it work for you on a different platform? Let us know!
Just going to say 'Me too!'? Don't clutter the database with that please !
Your email address:
MUST BE VALID
Solve the problem:
38 + 16 = ?
Subscribe to this entry?

 
 [2020-09-10 22:19 UTC] smitty7523 at yahoo dot com
Description:
------------
I am trying to insert a line in a file after a line that is searched for.
The line to insert is inserted fine, but the text after it gets truncated partially.

********* test.txt ************
PHP is a great language.
It is a tool for the ages.
It is easy to use and fast too!

Test script:
---------------
$absoluteFilePath = '<your_root_path>/test.txt';
$splFile = new \SplFileObject($absoluteFilePath, 'c+');
$splFile->flock(LOCK_EX);
$splFile->rewind();
		
// Add to next line.
while ($splFile->valid()) {
	$currentLine = $splFile->fgets();
	if (strpos($currentLine, "It is a tool for the ages.") !== false) {
		$splFile->fwrite("But it has a few bugs.\n");
	}
}
$splFile->flock(LOCK_UN);

Expected result:
----------------
PHP is a great language.
It is a tool for the ages.
But it has a few bugs.
It is easy to use and fast too!


Actual result:
--------------
PHP is a great language.
It is a tool for the ages.
But it has a few bugs.
ast too!

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2020-09-10 22:28 UTC] requinix@php.net
-Status: Open +Status: Not a bug
 [2020-09-10 22:28 UTC] requinix@php.net
File writes do not insert. That is not how files work.

If you want to insert then you have to read in everything that comes at and after your "insertion" point, write what you want to add, and then write out the rest of what was there.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Tue Apr 23 13:01:29 2024 UTC