Home  >  Article  >  Backend Development  >  PHP implementation code for reading and writing files

PHP implementation code for reading and writing files

WBOY
WBOYOriginal
2016-07-25 08:52:121209browse
  1. $fp = fopen("test.txt", "r");
  2. ?>
Copy code

2.fclose (close file) grammar: fclose(filepointer) filepointer, the file pointer to be closed. The fclose function returns TRUE if successful and FALSE if failed. Example:

  1. $fp = fopen("test.txt", "r");
  2. fclose($fp);
  3. ?>
Copy code

3.feof( Detects whether the end of file has been reached) grammar: feof(filepointer) filepointer, the file pointer to be detected, which must point to a file that was successfully opened but not closed. If the file pointer reaches the end of the file or an error occurs, the feof function returns TRUE. Example:

  1. $fp = fopen("test.txt", "r");
  2. while(! feof($fp))
  3. {
  4. echo fgets($fp). "< br />";
  5. }
  6. fclose($fp);
  7. ?>
Copy code

4.fgets (read a line from the file pointer) grammar: fgets(filepointer) filepointer, the file pointer to be read. Reads a line from the file and returns a string if successful, or FALSE if failed. Example:

  1. $fp = fopen("test.txt", "r");
  2. if($fp)
  3. {
  4. for($i=1;! feof($fp); $i++)
  5. {
  6. echo "line ".$i." : ".fgets($fp). "
    ";
  7. }
  8. }
  9. else
  10. {
  11. echo "Failed to open file";
  12. }
  13. fclose($fp);
  14. ?>
Copy code

Assume the content of test.txt is: hello world hello cnblogs hello heihaozi hello everyone The page output results are: Line 1: hello world Line 2: hello cnblogs Line 3: hello heihaozi Line 4: hello everyone

5.fwrite (write file) grammar: fwrite(filepointer,string) filepointer, the file pointer to be written. string, the string to be written. Returns the number of characters written if successful, or FALSE if failed. Example:

  1. $fp = fopen("test.txt", "w");//The file is cleared before writing
  2. if($fp)
  3. {
  4. $count=0;
  5. for($i=1;$i<=5;$i++)
  6. {
  7. $flag=fwrite($fp,"行".$i." : "."Hello World!rn");
  8. if( !$flag)
  9. {
  10. echo "Failed to write file
    ";
  11. break;
  12. }
  13. $count+=$flag;
  14. }
  15. echo "A total of ".$count." characters written";
  16. }
  17. else
  18. {
  19. echo "Failed to open file";
  20. }
  21. fclose($fp);
  22. ?>
Copy the code

The page output result is: Write a total of 100 characters

test.txt file will be written: Line 1: Hello World! Line 2: Hello World! Line 3: Hello World! Line 4: Hello World! Line 5: Hello World!



Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn