InfinityQuest - Programming Code Tutorials and Examples with Python, C++, Java, PHP, C#, JavaScript, Swift and more

Menu
  • Home
  • Sitemap

Python Programming Language Best Tutorials and Code Examples

Learn Python Right Now!
Home
PHP
Modifying a File in Place Without a Temporary File in PHP
PHP

Modifying a File in Place Without a Temporary File in PHP

InfinityCoder December 26, 2016

You want to change a file without using a temporary file to hold the changes.

Read the file with file_get_contents(), make the changes, and rewrite the file with file_put_contents():

1
2
3
$contents = file_get_contents('pickles.txt');
$contents = strtoupper($contents);
file_put_contents('pickles.txt', $contents);

This example turns text emphasized with asterisks or slashes into text with HTML <b> or <i> tags:

1
2
3
4
5
6
$contents = file_get_contents('message.txt');
// convert *word* to <b>word</b>
$contents = preg_replace('@\*(.*?)\*@i','<b>$1</b>',$contents);
// convert /word/ to <i>word</i>
$contents = preg_replace('@/(.*?)/@i','<i>$1</i>',$contents);
file_put_contents('message.txt', $contents);

Because adding HTML tags makes the file grow, the entire file has to be read into memory and then processed.

If the changes to a file make each line shrink (or stay the same size), the file can be processed line by line, saving memory.
For example, this converts text marked with <b> and <i> to text marked with asterisks and slashes:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
$fh = fopen('message.txt','r+')                  or die($php_errormsg);
 
// figure out how many bytes to read
$bytes_to_read = filesize('message.txt');
 
// initialize variables that hold file positions
$next_read = $last_write = 0;
 
// keep going while there are still bytes to read
while ($next_read < $bytes_to_read) {
 
  /* move to the position of the next read, read a line, and save
   * the position of the next read */
  fseek($fh,$next_read);
  $s = fgets($fh)                                  or die($php_errormsg);
  $next_read = ftell($fh);
 
  // convert <b>word</b> to *word*
  $s = preg_replace('@<b[^>]*>(.*?)</b>@i','*$1*',$s);
  // convert <i>word</i> to /word/
  $s = preg_replace('@<i[^>]*>(.*?)</i>@i','/$1/',$s);
 
  /* move to the position where the last write ended, write the
   * converted line, and save the position for the next write */
  fseek($fh,$last_write);
  if (-1 == fwrite($fh,$s))            { die($php_errormsg); }
  $last_write = ftell($fh);
}
 
// truncate the file length to what we've already written
ftruncate($fh,$last_write)                  or die($php_errormsg);
 
// close the file
fclose($fh)                                 or die($php_errormsg);

 

Share
Tweet
Email
Prev Article
Next Article

Related Articles

Printing Correct Plurals in PHP
You want to correctly pluralize words based on the value …

Printing Correct Plurals in PHP

Localizing Currency Values in PHP
You want to display currency amounts in a locale-specific format. …

Localizing Currency Values in PHP

About The Author

InfinityCoder
InfinityCoder

Leave a Reply

Cancel reply

Recent Tutorials InfinityQuest

  • Adding New Features to bash Using Loadable Built-ins in bash
    Adding New Features to bash Using Loadable …
    June 27, 2017 0
  • Getting to the Bottom of Things in bash
    Getting to the Bottom of Things in …
    June 27, 2017 0

Recent Comments

  • fer on Turning a Dictionary into XML in Python
  • mahesh on Turning a Dictionary into XML in Python

Categories

  • Bash
  • PHP
  • Python
  • Uncategorized

InfinityQuest - Programming Code Tutorials and Examples with Python, C++, Java, PHP, C#, JavaScript, Swift and more

About Us

Start learning your desired programming language with InfinityQuest.com.

On our website you can access any tutorial that you want with video and code examples.

We are very happy and honored that InfinityQuest.com has been listed as a recommended learning website for students.

Popular Tags

binary data python CIDR convert string into datetime python create xml from dict python dictionary into xml python how to create xml with dict in Python how to write binary data in Python IP Address read binary data python tutorial string as date object python string to datetime python

Archives

  • June 2017
  • April 2017
  • February 2017
  • January 2017
  • December 2016
  • November 2016
Copyright © 2021 InfinityQuest - Programming Code Tutorials and Examples with Python, C++, Java, PHP, C#, JavaScript, Swift and more
Programming Tutorials | Sitemap