3
中打开文件的函数为 fopen,该函数将返回一个资源对象,以存储当前的文件资源,语法如下:
Fopen(string
Fopen(string
Fopen(string
Fopen(string filename,string
filename,string
filename,string
filename,string mode)
mode)
mode)
mode)
Filename 为文件名或者文件所在的路径,mode 为文件的打开模式。
Fopen 函数中 mode 参数的取值
Mode 的值
说明
r
只读方式打开,文件指针指向文件头
r+
读写方式打开,将文件指针指向文件头
w
写入方式打开,如果文件存在则清空,不存在则创建
w+
读写方式打开,如果文件存在则清空,不存在则创建
a
写入方式打开,如果文件存在则追加,不存在则创建
a+
读写方式打开,如果文件存在则追加,不存在则创建
x
写入方式打开,如果文件存在则打开失败,不存在则创建
x+
读写方式打开,如果文件存在则打开失败,不存在则创建
关闭文件
中关闭文件的函数为 fclose,语法如下:
Void
Void
Void
Void fclose(file_resource)
fclose(file_resource)
fclose(file_resource)
fclose(file_resource)
file_resource 为使用 fopen 函数后返回的资源对象。
例如:
<?php
$file = fopen(“php\\php.txt”,”r”);
echo fgetc($file);
fclose($file);
?>
写入文件
中写入文件的函数为 fclose,语法如下:
Int
Int
Int
Int fclose(file_resource,string
fclose(file_resource,string
fclose(file_resource,string
fclose(file_resource,string str
str
str
str [,int
[,int
[,int
[,int length])
length])
length])
length])
file_resource 为使用 fopen 函数后返回的资源对象,str 为要写入的字符串,length 为指定的字符串长度。
例如:
<?php
$filename = “php\\php.txt”;
$file = fopen($filename,”w”);
fwrite($file,”This is www.phpdo.net\n”);
fwrite($file,”This is a php test\n”);
fclose($file);
?>
打开文件夹,可以看到里边有两行语句:This is
和 This is a php test。
读取文件
在
中最常用的读取文件的函数有三个:fgetc、fgets 和 fread。
Fgetc 函数用于读取文件中的一个字符,语法如下: