简体   繁体   English

文件中特定位置的PHP覆盖

[英]PHP Overwriting at a specific location in a file

I am trying to write a text at a specific position in a file that already has some content. 我试图在已经有一些内容的文件中的特定位置写入文本。 After writing I find the file truncated to the size of the text plus fseek position and the first characters with value 0. Is this the normal behaviour or am I missing something? 写入后,我发现该文件被截断为文本大小加上fseek位置和值为0的第一个字符的大小。这是正常现象还是我丢失了某些内容? I want to mention that I'm trying to avoid loading the file into memory and writing it back. 我想提到的是,我试图避免将文件加载到内存中并将其写回。

$file = fopen("text.txt","w");
fseek($file,3);
fwrite($file,"Hello");
fclose($file);

You need to open the file in c mode, else it's truncated on fopen : 您需要以c模式打开文件,否则它将在fopen被截断:

$file = fopen("text.txt","c");

See http://php.net/manual/de/function.fopen.php for a documentation of all file open modes and what exactly they do. 有关所有文件打开模式及其确切功能的文档,请参见http://php.net/manual/de/function.fopen.php Also see the http://www.php.net/manual/en/function.fseek.php manual 另请参见http://www.php.net/manual/zh/function.fseek.php手册

Yes this is normal behaviour : 是的,这是正常现象:

fopen($file, "w") : fopen($file, "w")

place the file pointer at the beginning of the file and truncate the file to zero length. 将文件指针放在文件的开头,并将文件截断为零长度。

fseek() : fseek()

In general, it is allowed to seek past the end-of-file; 通常,它允许查找文件末尾。 if data is then written, reads in any unwritten region between the end-of-file and the sought position will yield bytes with value 0 . 如果随后写入数据,则在文件末尾与查找位置之间的任何未写入区域中进行读取都会产生值为0的字节 [..] If you have opened the file in append (a or a+) mode, any data you write to the file will always be appended, regardless of the file position, and the result of calling fseek() will be undefined. [..]如果您以附加(a或a +)模式打开文件,则无论文件位置如何,都将始终附加写入文件的任何数据,并且调用fseek()的结果将不确定。

You probably want to open the file in a non truncating write mode (eg "c" but not "a" ). 您可能希望以非截断的写入模式打开文件(例如“ c”而不是“ a” )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM