fopen、fwrite、fprint、fread 和 fclose 命令可用于处理文件。
在读取或写入文件前,需要使用 fopen 函数打开文件。
fopen 返回文件控制柄。文件控制柄表示打开文件。应将该值保存到变量中,以使用 fprint 等其他命令打开文件。
$fileId = fopen($exampleFileName,"r");
一旦打开文件进行读取,就可以使用以下某个命令从文件读取数据:
| 目标 | 使用该命令 |
|---|---|
| 读取一行(读取到下一个新行)。 |
fgetline (fileID) |
| 读取字词(读取到下一个空格)。 |
fgetword (fileID) |
| 读取单个值。 |
fread (fileID,类型) |
// Read a file one line at a time
$fileId=fopen($exampleFileName,"r");
string $nextLine = `fgetline $fileId`;
while ( size( $nextLine ) > 0 ) {
print ( $nextLine );
$nextLine = `fgetline $fileId`;
}
如果处在文件末尾,feof <fileID> 函数将返回非零值。
string $nextWord = `fgetword $fileId`;
while ( !feof($fileId) ) {
print ( $nextWord + "\n" );
$nextWord = fgetword($fileId);
}
一旦打开文件进行写入或附加操作,便可以使用以下某个命令向文件写入数据:
$fileId = fopen($exampleFileName,"w"); fprint($fileId,"Hello there\n"); fclose($fileId);
fwrite 命令将二进制格式的数据参数写入文件。它将字符串作为 ASCII 写入,结尾带一个 NULL 字符。不应使用 fwrite 来写入文本文件或编写原始字节,除非结尾需要一个 NULL 字符。