PHP/File Directory/fgets
Содержание
- 1 Checking for an error from fopen(), fgets(), or fclose()
- 2 Counting paragraphs in a file
- 3 Counting records in a file
- 4 Creating and Using a File Class
- 5 fgets() function returns a string read from a file.
- 6 fgets.php
- 7 Processing a list of books
- 8 Processing each word in a file
- 9 Reading a compressed file
- 10 Reading a file a line at a time
Checking for an error from fopen(), fgets(), or fclose()
<?
$fh = fopen("data.txt","rb");
if (! $fh) {
print "Error opening people.txt: $php_errormsg";
} else {
for ($line = fgets($fh); ! feof($fh); $line = fgets($fh)) {
if ($line === false) {
print "Error reading line: $php_errormsg";
} else {
$line = trim($line);
$info = explode("|", $line);
print "<li><a href="mailto:" . $info[0] . "">" . $info[1] ."</li>\n";
}
}
if (! fclose($fh)) {
print "Error closing people.txt: $php_errormsg";
}
}
?>
//data.txt
a@example.ru|Alice
b@example.org|Bill
c@example.ru|Charlie
d@example.ru|Lewis
Counting paragraphs in a file
<?php
$paragraphs = 0;
if ($fh = fopen("great-american-novel.txt","r")) {
while (! feof($fh)) {
$s = fgets($fh);
if (("\n" == $s) || ("\r\n" == $s)) {
$paragraphs++;
}
}
}
print $paragraphs;
?>
Counting records in a file
<?php
$records = 0;
$record_separator = "--end--";
if ($fh = fopen("great-american-textfile-database.txt","r")) {
while (! feof($fh)) {
$s = rtrim(fgets($fh));
if ($s == $record_separator) {
$records++;
}
}
}
print $records;
?>
Creating and Using a File Class
<?php
// Copyright 2005, Lee Babin (lee@thecodeshoppe.ru)
// This code may be used and redistributed without charge
// under the terms of the GNU General Public
// License version 2.0 or later -- www.gnu.org
// Subject to the retention of this copyright
// and GPL Notice in all copies or derived works
class cfile {
//The path to the file you want to work with.
protected $thepath;
//Error messages in the form of constants for ease of use.
const FOUNDERROR = "Sorry, the file in question does not exist.";
const PERMERROR = "Sorry, you do not have the proper permissions on this file";
const OPENERROR = "Sorry, the file in question could not be opened.";
const CLOSEERROR = "Sorry, the file could not be closed.";
//The constructor function.
public function __construct (){
$num_args = func_num_args();
if($num_args > 0){
$args = func_get_args();
$this->thepath = $args[0];
}
}
//A function to open the file.
private function openfile ($readorwrite){
//First, ensure the file exists.
try {
if (file_exists ($this->thepath)){
//Now, you need to see if you are reading or writing or both.
$proceed = false;
if ($readorwrite == "r"){
if (is_readable($this->thepath)){
$proceed = true;
}
} elseif ($readorwrite == "w"){
if (is_writable($this->thepath)){
$proceed = true;
}
} else {
if (is_readable($this->thepath) && is_writable($this->thepath)){
$proceed = true;
}
}
try {
if ($proceed){
//You can now attempt to open the file.
try {
if ($filepointer = fopen ($this->thepath, $readorwrite)){
return $filepointer;
} else {
throw new exception (self::OPENERROR);
return false;
}
} catch (exception $e) {
echo $e->getmessage();
}
} else {
throw new exception (self::PERMERROR);
}
} catch (exception $e) {
echo $e->getmessage();
}
} else {
throw new exception (self::FOUNDERROR);
}
} catch (exception $e) {
echo $e->getmessage();
}
}
//A function to close a file.
function closefile () {
try {
if (!fclose ($this->thepath)){
throw new exception (self::CLOSEERROR);
}
} catch (exception $e) {
echo $e->getmessage();
}
}
//A function to read a file, then return the results of the read in a string.
public function read () {
//First, attempt to open the file.
$filepointer = $this->openfile ("r");
//Now, return a string with the read data.
if ($filepointer != false){
//Then you can read the file.
return fread ($filepointer,filesize ($this->thepath));
}
//Lastly, close the file.
$this->closefile ();
}
//A function to write to a file.
public function write ($towrite) {
//First, attempt to open the file.
$filepointer = $this->openfile ("w");
//Now, return a string with the read data.
if ($filepointer != false){
//Then you can read the file.
return fwrite ($filepointer, $towrite);
}
//Lastly, close the file.
$this->closefile ();
}
//A function to append to a file.
public function append ($toappend) {
//First, attempt to open the file.
$filepointer = $this->openfile ("a");
//Now, return a string with the read data.
if ($filepointer != false){
//Then you can read the file.
return fwrite ($filepointer, $toappend);
}
//Lastly, close the file.
$this->closefile ();
}
//A function to set the path to a new file.
public function setpath ($newpath) {
$this->thepath = $newpath;
}
}
?>
<?php
//Include the class.
require_once ("file.class.inc.php");
//Then create a new instance of the class.
$myfile = new cfile ("data.txt");
//Now, let"s try reading it.
echo $myfile->read();
//Then let"s try writing to the file.
$myfile->write ("Hello World!");
//Then, let"s try appending.
$myfile->append ("Hello Again!");
?>
fgets() function returns a string read from a file.
Its syntax is: string fgets (int filepointer, int length)
<?
$fh = fopen("data.txt", "r");
while (! feof($fh)) :
$line = fgets($fh, 4096);
print $line."<br>";
endwhile;
fclose($fh);
?>
fgets.php
<?php
$fh = fopen("/home/www/data/users.txt", "rt");
while (!feof($fh)) echo fgets($fh);
fclose($fh);
?>
Processing a list of books
<?php
$fh = fopen("books.txt","r") or die("can"t open: $php_errormsg");
while (! feof($fh)) {
$s = rtrim(fgets($fh));
list($title,$author,$publication_year) = explode("|",$s);
}
fclose($fh) or die("can"t close: $php_errormsg");
?>
Processing each word in a file
<?php
$fh = fopen("novel.txt","r") or die($php_errormsg);
while (! feof($fh)) {
if ($s = fgets($fh)) {
$words = preg_split("/\s+/",$s,-1,PREG_SPLIT_NO_EMPTY);
}
}
fclose($fh) or die($php_errormsg);
?>
Reading a compressed file
<?php
$fh = fopen("compress.zlib://lots-of-data.gz","r") or die("can"t open: $php_errormsg");
while ($line = fgets($fh)) {
// $line is the next line of uncompressed data
}
fclose($fh) or die("can"t close: $php_errormsg");
?>
Reading a file a line at a time
<?
$fh = fopen("people.txt","rb");
for ($line = fgets($fh); ! feof($fh); $line = fgets($fh)) {
$line = trim($line);
$info = explode("|", $line);
print "<li><a href="mailto:" . $info[0] . "">" . $info[1] ."</li>\n";
}
fclose($fh);
?>
//people.txt
a@example.ru|Alice
b@example.org|Bill
c@example.ru|Charlie
d@example.ru|Lewis