开发者

How to write a string at the beginning of txt files massively?

I have 100 txt files on my webserver. I have to insert a string e.g. abcdef on the beginning of all of them using php and save th开发者_JS百科em back again. How is this possible ?


Well, google found this.

function prepend($string, $filename) {
    $context = stream_context_create();
    $tmpname = tempnam(".");

    $fp = fopen($filename, "r", 1, $context);
    file_put_contents($tmpname, $string);
    file_put_contents($tmpname, $fp, FILE_APPEND);
    fclose($fp);

    unlink($filename);
    rename($tmpname, $filename);
}

So you call prepend($string, $filename) for every file and you're done.


Look at opendir, glob, fopen, and fwrite. For example:

foreach (glob("*.txt") as $file) {
   $fh = fopen($file, 'c'); //Open file for writing, place pointer at start of file.
   fwrite($fh, 'abcdef');
   fclose($fh);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜