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
Welcome! If you don't have a Git account, you can't do anything here.
You can add a comment by following this link or if you reported this bug, you can edit this bug over here.
(description)
Block user comment
Status: Assign to:
Package:
Bug Type:
Summary:
From: smitty7523 at yahoo dot com
New email:
PHP Version: OS:

 

 [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: Sat Apr 20 05:01:27 2024 UTC