PHP file read-write operation correlation function Summary _php skill

Source: Internet
Author: User
Tags fread readfile

One, fwrite () write file

It is easier to save data in a program to a file, using the fwrite () function to write the contents of the string to a file. In a file, a newline character is represented by a sequence of characters, representing the end of a line in a file. Keep this in mind when you need to enter or output one line of information at a time. Different operating systems have different end symbols, and unix-based systems use "\ n" as the line end character, and the windows-based system uses "\ r \ n" as the line end character, and the Macintosh based system uses "\ r" as the line ending character. When you want to write a text file and want to insert a new row, you need to use the line end symbol for the appropriate operating system. The prototype of the function fwrite () looks like this:

Copy Code code as follows:

int fwrite (Resource handle,string string[,int length])//write file

The first parameter needs to provide a file resource opened by the fopen () function that outputs the string content supplied by the second argument to the resource specified by the first parameter. If the third optional argument lenth,fwrite () is given, it will stop when the length character is written. Otherwise, it is written until the end of the content is reached. If you write less than the length of a byte, the function stops after you have finished writing all of the content. function fwrite () returns the number of characters written after the execution completes, false when an error occurs. The following code is an example of writing to a file.

Copy Code code as follows:

<?php
Declare a variable to save the file name
$fileName = "Data.txt";
Use the fopen () function to open a file in write-only mode, create it if it does not exist, and then open it by using the program
$handle = fopen ($fileName, ' w ') or Die (' Open <b> '. $fileName. ') </br> file failed!! ');
Looping 10 times to write 10 rows of data into a file
For ($row =0 $row <10; $row + +) {
Fwrite ($handle, $row. ": www.lampbrother.net\n");
}
Fclose ($handle);
?>

After the program executes, if there are data.txt files in the current directory, empty the file and write 10 rows of data. If no Data.txt file exists, the file is created and 10 rows of data are written. Alternatively, you can use the fputs () function, which is an alias function of the fwrite () function, if you need to write files quickly, you can use the file_put_contents () function, and then call fopen (), fwrite (), and fclose () Functions of the same function. The use code for the function is as follows:

Copy Code code as follows:

<?php
Declare a variable to save the file name
$fileName = "Data.txt";
Declares that a variable is used to save data in a written file
$data = "A total of 10 rows of data \ n";
For ($row =0 $row <10; $row + +) {
Store 10 data in a string variable
$data. = $row. ": www.lampbrother.net\n";
}
Write all data to the specified file at once
File_put_contents ($fileName, $data);
?>

This function can write data directly to the specified file. If you call multiple times at the same time and write data to the same file, only the last data written by that function is saved in the file. Because every time you drop yo oh that will reopen the file and the file in the middle of the data empty, so you can not like the first program to write more than a row of data.

Second, read the contents of the file

There are a number of standard functions for reading content from files in PHP, and you can choose which function to use in your program based on their functional characteristics. These function functions and their descriptions are shown in the following table.

When reading a file, pay attention not only to the line end symbol "\ n", but also to a standard way to identify when the end of the file is reached, a standard that usually becomes the EOF character. EOF is a very important concept, and in almost every mainstream programming language, the corresponding built-in function is provided to analyze whether or not a file EOF has been reached. In PHP, use the feof () function. This function accepts an open file resource, determines whether a file pointer is at the end of the file, and returns True if it is at the end of the file.

① function Fread ()

This function is used to read a string of a specified length in an open file. You can also safely use binary files, and the mode parameter of the fopen () function is added ' B ' When you open a file on a system that distinguishes binary and text files (such as Windows). The prototype of the function fread () looks like this:

Copy Code code as follows:

string fread (int handle,int length)/Read Open file

This function reads up to length bytes from the file pointer resource handle. When you finish reading length bytes, or when you arrive at EOF, or (for network streams), when a package is available, you stop reading the file, and you see what happens first. The function returns a read string of content and False if it fails. The use code for the function is as follows:
Copy Code code as follows:

<?php
Reads the specified number of bytes from a file into a variable
$filename = "Data.txt";
$handle = fopen ($filename, ' r ') or Die ("File open failed");
$contents = fread ($handle, 100); Reads 100 bytes from a file
Fclose ($handle); To close a file resource
Echo $contents; Output of content to be read from file

Reads all content from a file into a variable, reads a part at a time, loops through the Read
$filename = "C:\\files\\somepic.gif";
$handle = fopen ($filename, ' RB ') or Die ("File open failed"); In a read-only way, the pattern adds ' B '
$contents = "";
while (!feof ($handle)) {//Use feof () to determine end of file
$contents. =fread ($handle, 1024); Read 1024 bytes at a time
}
Fclose ($handle); To close a file resource
Echo $contents; All content that will be read from the file is output

Another way to read all the content from a file
$filename = "Data.txt";
$handle = fopen ($filename, "R") or Die ("File open failed");
$contents = Fread ($handle, FileSize ($filename)); Read together using the Fielsize () function
Fclose ($handle);
Echo $contents;
?>

If you just want to read the contents of a file into a string, you can use the file_get_contents () function, which is much better than the code above. The file_get_contents () function is the preferred method for reading the contents of a file into a string, and memory-mapping techniques are used to enhance performance if supported by the operating system. The use code for the function is as follows:

Copy Code code as follows:

<?php
Echo file_get_contents ("Data.txt"); Reads the contents of a text file and outputs
Echo file_get_contents ("C:\\files\\somepic.gif"); Read the contents of binary files and output
?>

② function fgets (), fgetc ()

Fgets () The function reads at most one row from the open file resource at a time. The prototype of the function fgets () looks like this:

Copy Code code as follows:

String fgets (int handle[,int length])//return row from open file

The first parameter provides a resource that is opened using the fopen () function. If the second optional parameter length is provided, the function returns length-1 bytes. or any content that is read before a newline or EOF is encountered. If you omit the optional length parameter, the default is 1024 characters. In most cases, this means that the fgets () function reads to 1024 characters match either encounters a newline symbol, so each successful call returns to the next line. Returns False if the read fails. The use code for the function is as follows:
Copy Code code as follows:

<?php
$handle = fopen ("Data.txt", "R") or Die ("File open failed"); Open a file in read-only mode
while (!feof ($handle)) {
$buffer = Fgets ($handle, 4096); Read one line at a time
echo $buffer. " <br> "; Output each flight
}
Fclose ($handle);
?>

function fgetc () reads only one character at the current pointer position in an open file resource. Returns a value of False if EOF is encountered with the file end flag. The use code for the function is as follows:

Copy Code code as follows:

<?php
$fp = fopen (' data.txt ', ' r ') or Die ("File open failed");
while (false!== ($char = fgetc ($fp))) {
echo $char. " <br> ";
}
?>

③ function file ()

This function is useful, similar to file_get_contents (), and does not require the use of the fopen () function to open the file, but the file () function can read the entire document into an array. Each element in the array corresponds to the corresponding row in the file, and the elements are split by a newline character, while the newline character is still appended to the end of each element. This allows the contents of the file to be processed using the associated functions of the array. The use code for the function is as follows:

Copy Code code as follows:

<?php
Reads the contents of the file Test.txt into an array and outputs
Print_r (file (test.txt));
?>

④ function ReadFile ()

The function can read the entire file specified, output to the output buffer immediately, and return the number of bytes read. The function also does not need to open the file using the fopen () function. In the following example, the contents of the file are easily exported to the browser. The code looks like this:

Copy Code code as follows:

<?php
Read and output data directly from the file data.txt to the browser
ReadFile ("Data.txt");
?>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.