Ted
Ted

Reputation: 3885

changing a file's single character

I need to change a single character in a file.
I'd rather not use an auxiliary file like so (pseudo code):
read(theFile)

change(theFile)

write(theFile2)

erase(theFile)

rename(theFile2,theFile)

Since in this way, Some process can require that file when it is actually erased.
Rather, I'd like to operate on that own file, because this way, I count on the server's os to take care of timing and process access to the file.

Upvotes: 2

Views: 112

Answers (2)

Femi
Femi

Reputation: 64700

In place editing is possible, but depending on what you want can be quite difficult. For example, this code:

<?php

$r = fopen("test.txt", "c+");
fseek($r, 50);

// write out
fwrite($r, "TESTING");
fclose($r);

will open up a file called test.txt and insert the word TESTING into the file 50 bytes in. Once you close the handle the file will be saved with the changes: no need to do a full on replace. In this way you can add data to the internals of the file. I could not see in any of the PHP functions a way to remove parts of the file, so if you need to delete anything you're probably out of luck and will have to overwrite the entire file.

EDIT: this requires PHP 5.2.6 or higher, as far as I can tell from the fopen docs.

Upvotes: 1

Daan
Daan

Reputation: 3348

You'll want to use flock to lock the file. Example based on code from the PHP docs:

<?php

$fp = fopen("file.txt", "r+");

if (flock($fp, LOCK_EX)) {  // acquire an exclusive lock
    //make your changes
    fflush($fp);            // flush output before releasing the lock
    flock($fp, LOCK_UN);    // release the lock
} else {
    echo "Couldn't get the lock!";
}

fclose($fp);

?>

Upvotes: 4

Related Questions