Heim  >  Artikel  >  Backend-Entwicklung  >  php 读写文件的实现代码

php 读写文件的实现代码

WBOY
WBOYOriginal
2016-07-25 08:52:121209Durchsuche
  1. $fp = fopen("test.txt", "r");
  2. ?>
复制代码

2.fclose(关闭文件) 语法: fclose(filepointer) filepointer,要关闭的文件指针。如果成功,fclose 函数返回 TRUE,如果失败,fclose 函数返回 FALSE。 示例:

  1. $fp = fopen("test.txt", "r");
  2. fclose($fp);
  3. ?>
复制代码

3.feof(检测是否已到达文件末尾) 语法: feof(filepointer) filepointer,要检测的文件指针,该指针必须指向成功打开没有关闭的文件。如果文件指针到了文件末尾或者出错时,feof函数返回 TRUE。 示例:

  1. $fp = fopen("test.txt", "r");
  2. while(! feof($fp))
  3. {
  4. echo fgets($fp). "
    ";
  5. }
  6. fclose($fp);
  7. ?>
复制代码

4.fgets(从文件指针中读取一行) 语法: fgets(filepointer) filepointer,要读取的文件指针。如果成功,从文件中读取一行并返回字符串,如果失败,返回 FALSE。 示例:

  1. $fp = fopen("test.txt", "r");
  2. if($fp)
  3. {
  4. for($i=1;! feof($fp);$i++)
  5. {
  6. echo "行".$i." : ".fgets($fp). "
    ";
  7. }
  8. }
  9. else
  10. {
  11. echo "打开文件失败";
  12. }
  13. fclose($fp);
  14. ?>
复制代码

假设test.txt的内容为: hello world hello cnblogs hello heihaozi hello everyone 页面输出的结果为: 行1 : hello world 行2 : hello cnblogs 行3 : hello heihaozi 行4 : hello everyone

5.fwrite(写入文件) 语法: fwrite(filepointer,string) filepointer,要写入的文件指针。string,要写入的字符串。如果成功,返回写入的字符数,如果失败,返回 FALSE。 示例:

  1. $fp = fopen("test.txt", "w");//文件被清空后再写入
  2. if($fp)
  3. {
  4. $count=0;
  5. for($i=1;$i{
  6. $flag=fwrite($fp,"行".$i." : "."Hello World!\r\n");
  7. if(!$flag)
  8. {
  9. echo "写入文件失败
    ";
  10. break;
  11. }
  12. $count+=$flag;
  13. }
  14. echo "共写入".$count."个字符";
  15. }
  16. else
  17. {
  18. echo "打开文件失败";
  19. }
  20. fclose($fp);
  21. ?>
复制代码

页面输出的结果为: 共写入100个字符

test.txt文件会被写入: 行1 : Hello World! 行2 : Hello World! 行3 : Hello World! 行4 : Hello World! 行5 : Hello World!



Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn