Đang chuẩn bị nút TẢI XUỐNG, xin hãy chờ
Tải xuống
Cập nhật tập tin Thường thì bạn sẽ muốn thêm nhiều dữ liệu hơn vào một tập tin đã lưu, bạn có thể làm theo nhiều cách. Bạn có thể sử dụng một trong các chế độ ghi thêm (xem Bảng 7-5), hoặc bạn chỉ có thể mở một tập tin để đọc và viết với một trong các phương thức khác có hỗ trợ bằng văn bản, và di chuyển con trỏ tập tin đến vị trí chính xác trong các tập tin mà bạn muốn viết hoặc đọc từ. . | As with moving a file a warning message will be displayed if the file doesn t exist which you can avoid by using file_exists to first check for its existence before calling unlink. Updating Files Often you will want to add more data to a saved file which you can do in many ways. You can use one of the append write modes see Table 7-5 or you can simply open a file for reading and writing with one of the other modes that supports writing and move the file pointer to the correct place within the file that you wish to write to or read from. The file pointer is the position within a file at which the next file access will take place whether it s a read or a write. It is not the same as the file handle as stored in the variable fh in Example 7-4 which contains details about the file being accessed. You can see this in action by typing in Example 7-11 and saving it as update.php. Then call it up in your browser. Example 7-11. Updating a file php update.php fh fopen testfile.txt r or die Failed to open file text fgets fh fseek fh 0 SEEK_END fwrite fh text or die Could not write to file fclose fh echo File testfile.txt successfully updated What this program does is open testfile.txt for both reading and writing by setting the mode with r which puts the file pointer right at the start. It then uses the fgets function to read in a single line from the file up to the first line feed . After that the fseek function is called to move the file pointer right to the file end at which point the line of text that was extracted from the start of the file stored in text is then appended to file s end and the file is closed. The resulting file now looks like this Line 1 Line 2 Line 3 Line 1 The first line has successfully been copied and then appended to the file s end. As used here in addition to the fh file handle the fseek function was passed two other parameters 0 and SEEK_END. The SEEK_END tells the function to move the file pointer to the end of the file and the 0 parameter tells