改变一个文件的单个字符 [英] changing a file's single character

查看:97
本文介绍了改变一个文件的单个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要更改文件中的单个字符。

我宁愿不使用像这样的辅助文件(伪代码):

read(theFile)



change(theFile)

$ b $ (theFile)

$ b $ p $ e $ e $ e $ e $ e $ e $ e $ e $



rename(theFile2,theFile)



由于这样,有些进程可以在实际擦除时需要该文件。
相反,我想操作自己的文件,因为这样,我指望服务器的操作系统负责处理对文件的访问。

解决方案

您需要使用 flock 来锁定文件。基于 PHP文档的代码示例:

 <?php 

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

if(flock($ fp,LOCK_EX)){//获得排他锁
//进行更改
fflush($ fp); //在释放锁之前刷新输出
flock($ fp,LOCK_UN); //释放锁
} else {
echo无法获得锁!
}

fclose($ fp);

?>


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.

解决方案

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);

?>

这篇关于改变一个文件的单个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆