PHP file processing classes Splfileobject and Splfileinfo

Source: Internet
Author: User
Tags flock

File Processing classes:
Splfileinfo {/* Method */public __construct (String $file _name) public int getatime (void)//Get last access time for file public string g Etbasename ([string $suffix])//Gets the base name of the file without path information, the parameter can be a file suffix, and if there is a parameter returns the base name of the file without that suffix. public int getctime (void)//Returns the timestamp of the last change in the article. public string getextension (void)//Gets the file name extension public splfileinfo getfileinfo ([string $class _name])//Returns the file path and name as an object  public string GetFileName (void)//Get file name without path public int getgroup (void)//Get file group, return group Idpublic int Getinode (void )//Get File Index node public string getlinktarget (void)//Get file link target public int getmtime (void)//Get last Modified time public int Getowne R (void)//Gets the owner of the file public string getpath (void)//Gets the file path, without the file name and the last slash public Splfileinfo getpathinfo ([string $CL Ass_name])//Return Path object public string getpathname (void)//Get file path public int getperms (void)//Get file permissions public string g Etrealpath (void)//Get file absolute path, if file does not exist, return falsepublic int getsize (void)//Return file size, Unit bytes public string getType (void)/ /return file type, mayis file, link, dirpublic bool isdir (void)//Determine if it is a directory, is put back to true otherwise return falsepublic bool IsExecutable (void)//Judge whether the file can be executed, return TR UE, otherwise return falsepublic bool Isfile (void)//If the file exists and is a normal file (not a link), returns True, otherwise returns falsepublic bool Islink (void)//Determine if the file is a connection,  Not return falsepublic bool IsReadable (void)//Determine whether the file is readable, readable return truepublic bool iswritable (void)//Determine if the file is writable, writable return Truepublic Splfileobject openFile ([string $open _mode = "R" [, bool $use _include_path = False [, resource $context = NULL]])//Received Fetch file object information public void Setfileclass ([string $class _name = ' Splfileobject "]) public void Setinfoclass ([string $class _name = "Splfileinfo"]) public void __tostring (void)//Returns the file path and name as a string}

How to use:

$info = new Splfileinfo ($file _name);

Splfileobject {/* constant */const integer drop_new_line = 1; Const integer READ_AHEAD = 2; Const integer SKIP_EMPTY = 4; const The integer read_csv = 8;/* Method */public String|array current (void)//Returns the contents of the present line of the file public bool eof (void)//detect if the file is to the end, if Returns true to the end, otherwise returns falsepublic bool Fflush (void)///outputs buffered content to a file, returns true on success, or FALSE on failure. public string fgetc (void)//read file by character public array fgetcsv ([String $delimiter = "," [, String $enclosure = "\" "[, str ing $escape = "\ \"]])//Read CSV file public string fgets (void)//Read file by row public string Fgetss ([string $allowable _tags  ])//Read the file by line and remove HTML markup public bool Flock (int $operation [, int & $wouldblock])//File lock or unlock, return TRUE or false/* parameter: lock_sh Shared lock (Read). LOCK_EX exclusive Lock (write). Lock_un release Lock (shared or exclusive).   LOCK_NB (Additional lock) If you do not want flock () to block when locked, you should add a lock after the above lock (not supported on Windows) flock (LOCK_EX+LOCK_NB); Exclusive lock plus additional lock flock (LOCK_UN+LOCK_NB); */public int Fpassthru (void)//output file pointer after all data and characters public int fputcsv (array $fields)//One-dimensional array is entered as a row in the CSV file, returning the length of the write string or FA Lsepublic string fread (int $length)//reads the specified number of bytes from the file, returns the read string or Falsepublic mixed fscanf (string $format [, mixed &$ ...] Reads a row from the file and resolves the/* example in the specified mode: $file = new Splfileobject ("Misc.txt"); while ($userinfo = $file->fscanf ("%s%s%s") {List ($    Name, $profession, $countrycode) = $userinfo; Do something with $name $profession $countrycode}*/public int fseek (int $offset [, int $whence = Seek_set])//move by Byte The file pointer position,/*seek_set sets the file pointer to the specified byte position (the default is the mode). Seek_cur sets the file pointer to the current position plus the specified byte position. Seek_end sets the file pointer to the end of the file with the specified byte position (the bytes are often negative). Public array fstat (void)//Gets the file information, returns the *//* numeric subscript associated key name as an array (from PHP 4.0.6) Description 0devdevice number-device name 1inoinode number-inode numbers 2modeinode protection Mode-inode protected Mode 3nlinknumber of links-was Number of connections 4uiduserid of owner-user id5gidgroupid of owner-owner group Id6rdevdevice type, if inode device *-device type, if Inode device 7sizesize in bytes-bytes of file size 8atimetime of last access (Unix timestamp)-Previous access Time (Unix timestamp) 9mtimetime of modification (Unix timestamp)-Last modified Time (Unix timestamp) 10ctimetimeof last Changes (Unix timestamp)-Time to Change (Unix timestamp) 11blksizeblocksize of filesystem IO *-file system io block size 12blocksnumber of BL Ocks allocated-the number of occupied blocks * is always 0 under Windows. *-Valid only on systems that support the st_blksize type. Other systems (such as Windows) return-1. */public int Ftell (void)//Returns the current file position, file pointer position public bool Ftruncate (int $size)//truncates the file to the specified length, if the length is greater than the length of the file is empty (the file open method has a shadow public int fwrite (string $str [, int $length])//writes $STR string to the file, write $length length only. Put back the number of bytes written or nullpublic array getcsvcontrol (void)//gets the delimiter and enclosure character used for parsing CSV fields.  public int getflags (void)//gets the flags set for a instance of Splfileobject as an integer.public int getmaxlinelen (void)//Returns the maximum number of bytes read in a row (if set), default is 0public int key (void)//Gets the current line number, if not set. public void Next (void)//move to the next line public void rewind (void)//Return to the first line public void seek (int $line _pos)//Navigate to the file to specify the line Publi c void Setcsvcontrol ([String $delimiter = "," [, String $enclosure = "\" "[, string $escape =" \ \ "]]) public void SETF Lags (int $flags public void Setmaxlinelen (int $max _len)//Set file reads the maximum number of bytes of a row, if the file has 10 characters per line, but sets the maximum read to public bool valid (void)//Check whether the file bottom is reached Part, not reaching the bottom returns TRUE, Arrival returns FALSE.}



Usage:

$file = new Splfileobject ("Misc.txt", ' r+ ');
while (! $file->eof ()) {
echo $file->current ();
$file->next ();
}

Common file processing methods:

<span style= "FONT-SIZE:18PX;" ><span style= "FONT-SIZE:18PX;" >/** * Get file specifies the number of rows range data * @param unknown $filename file name * @param number $startLine start line * @param number $endLine End line * @param string $method * @return Multitype: */function getfilelines ($filename, $startLine = 1, $endLine = A, $method = ' RB    ') {$content = array ();    $count = $endLine-$startLine;    $fp = new Splfileobject ($filename, $method); $FP->seek ($startLine-1); Go to Nth row, the Seek method parameter counts from 0 for ($i = 0; $i <= $count; + + $i) {$content [] = $fp->current ();//current () get the Forward Content $fp->next ();            The next line if ($fp->eof ()) {Array_pop ($content);        Break }} return Array_filter ($content); Array_filter filter: False,null, '}/** * get the last line of the article * @param string $res file path/name */function Get_last_line ($res) {$fp = FOP    En ($res, ' R ');    if (false = = $fp) {return ' error ';    } fseek ($fp, -1,seek_end);    $s = "; while (($c = fgetc ($fp))!== false)   {if ($c = = "\ n" && $s) break; $s = $c.        $s;    Fseek ($FP,-2, seek_cur);    } fclose ($FP); return $s;} </span></span>


PHP file processing classes Splfileobject and Splfileinfo

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.