fwrite()介绍
fwrite() 函数用于向文件写入字符串,成功返回写入的字符数,否则返回 FALSE 。
语法:
int fwrite( resource handle, string string [, int length] )
fwrite() 把 string 的内容写入文件指针 handle 处。
参数:
参数
说明
handle
要写入字符串的文件指针,一般由 fopen() 函数创建
data
要写入的字符串
length
可选,规定要写入的最大字节数
如果指定了可选参数 length,当写入了 length 个字节或者写完了 string 以后,写入就会停止。
fwrite()实例
1.使用fwrite()函数向文件中追加数据:
$myfile = "./test.txt";
$openfile = fopen ($myfile,"w") or die ("Couldn't open the file");
fwrite ($openfile,"This is a string \n");
fclose ($openfile);
$openfile = fopen ($myfile,"r") or die ("Couldn't open the file");
$file_size=filesize($myfile);
$file_contents = fread ($openfile,$file_size);
$msg ="$file_contents";
fclose ($openfile);
echo $msg;
?>
2.使用fwrite 换行写入
如果要在文件中实现换行写入,只需要在写入内容中需要换行的地方添加换行符 n 即可:
$filename = 'file.txt';
$word = "manongjc.com!n";
$fh = fopen($filename, "a");
echo fwrite($fh, $word);
fclose($fh);
?>
3.在fwrite函数中使用length参数限制写入的最大字节数
// 要写入的文件名字
$filename = 'file.txt';
// 写入的字符
/* http://www.manongjc.com/article/1393.html */
$word = "manongjc.com!";
$fh = fopen($filename, "w");
echo fwrite($fh, $word,4);
fclose($fh);
?>