How does the append mode in fopen affect the atomicity of fwrite operations in PHP?

When using the append mode ('a') in fopen in PHP, fwrite operations are not atomic. This means that multiple fwrite operations can overlap and potentially corrupt the data being written. To ensure atomicity, you can use file locking mechanisms such as flock() to prevent concurrent writes.

$fp = fopen('file.txt', 'a');
if (flock($fp, LOCK_EX)) {
    fwrite($fp, "Data to be written\n");
    flock($fp, LOCK_UN);
} else {
    echo "Could not lock file!";
}
fclose($fp);