fwrite()介绍
fwrite() 函数用于向文件写入字符串,成功返回写入的字符数,否则返回 FALSE 。
语法:
int fwrite( resource handle, string string [, int length] )
fwrite() 把 string 的内容写入文件指针 handle 处。
参数:
| 参数 | 说明 |
|---|---|
| handle | 要写入字符串的文件指针,一般由 fopen() 函数创建 |
| data | 要写入的字符串 |
| length | 可选,规定要写入的最大字节数 |
如果指定了可选参数 length,当写入了 length 个字节或者写完了 string 以后,写入就会停止。
fwrite()实例
1.使用fwrite()函数向文件中追加数据:
<?php
$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 即可:
<?php
$filename = \'file.txt\';
$word = \"manongjc.com!n\";
$fh = fopen($filename, \"a\");
echo fwrite($fh, $word);
fclose($fh);
?>
3.在fwrite函数中使用length参数限制写入的最大字节数
<?php
// 要写入的文件名字
$filename = \'file.txt\';
// 写入的字符
/* http://www.manongjc.com/article/1393.html */
$word = \"manongjc.com!\";
$fh = fopen($filename, \"w\");
echo fwrite($fh, $word,4);
fclose($fh);
?> 继续阅读与本文标签相同的文章
-
小鹏P7售价28.3-39.6万元,何小鹏称Model 3毫无竞争力
2026-05-14栏目: 教程
-
Vision M NEXT 概念车,宝马面向“未来”的产品张什么样?
2026-05-14栏目: 教程
-
大反转!谷歌态度开始“服软”,华为即将获得GMS许可
2026-05-14栏目: 教程
-
Python 超简单实现9种图像风格迁移
2026-05-14栏目: 教程
-
华为打回欧洲市场!HMS取得重大成功,大量APP接入!谷歌慌不慌?
2026-05-14栏目: 教程
