MANUAL DE PHP

(y algo mas)windsurf pozo izquierdo
Google
search for in the  
ELMARRAJO.COM mysql bulma desarrollo web linux fedora html ayuda

windsurf mercedes camper

fseek

(PHP 3, PHP 4, PHP 5)

fseek -- Realiza una búsqueda sobre un apuntador de archivo

Descripción

int fseek ( resource gestor, int desplazamiento [, int desde] )

Establece el indicador de posición para el archivo referenciado por gestor. La nueva posición, medida en bytes desde el comienzo del archivo, so obtiene al sumar desplazamiento con la posición especificada por desde, cuyos valores se definen como se indica a continuación:

SEEK_SET - Define la posición igual a desplazamiento bytes.
SEEK_CUR - Define la posición como la posición actual más desplazamiento.
SEEK_END - Define la posición como el final-de-archivo más desplazamiento. (Para moverse a una posición anterior al final-de-archivo, es necesario pasar un valor negativo en desplazamiento.)

Si no se especifica desde, se asume que sea SEEK_SET.

De tener éxito, la función devuelve 0; de lo contrario devuelve -1. Note que realizar una reubicación más allá del final de archivo no se considera un error.

Ejemplo 1. Ejemplo de fseek()

<?php

$da
= fopen('algun_archivo.txt', 'r');

// leer datos
$datos = fgets($da, 4096);

// moverse de vuelta al comienzo del archivo
// igual que rewind($da);
fseek($da, 0);

?>

Puede que no sea posible usar la función sobre apuntadores de archivo devueltos por fopen() si usan los formatos "http://" o "ftp://". fseek() produce también resultados indefinidos para secuencias de adición (abiertas con la bandera "a").

Nota: El argumento desde fue agregado después de PHP 4.0.0.

Nota: Si el archivo es abierto en modo de adición ("a" o "a+"), cualquier información escrita en el archivo será siempre agregada al final, independientemente de la posición en el archivo.

Vea también ftell() y rewind().



add a note add a note User Contributed Notes
fseek
marc dot roe at gmail dot com
19-Aug-2006 09:38
I tried to improve and modify (mail at ulf-kosack dot de)'s function. Actually it is very fast, i.e. requires much less time than to get the last five, ten or whatever lines of a file using file() ore file_get_contents().

function read_file($file, $lines)
{
       $handle = fopen($file, "r");
       $linecounter = $lines;
       $pos = -2;
       $beginning = false;
       $text = array();
       while ($linecounter > 0) {
         $t = " ";
         while ($t != "\n") {
           if(fseek($handle, $pos, SEEK_END) == -1) {
$beginning = true; break; }
           $t = fgetc($handle);
           $pos --;
         }
         $linecounter --;
         if($beginning) rewind($handle);
         $text[$lines-$linecounter-1] = fgets($handle);
         if($beginning break;
       }
       fclose ($handle);
       return array_reverse($text); // array_reverse is optional: you can also just return the $text array which consists of the file's lines.
}

The good thing now is, that you don't get an error when your requesting more lines than the file contains. In this case the function will just return the whole file content.
lucky at somnius dot com dot ar
18-Aug-2006 05:35
Jim's (jim at lfchosting dot com) code for the last-line issue is perfect if the file is not empty, or moreover if it has more than one line. However if the file you're using cotains no new-line character at all (i.e. it is empty or it's got one line and only one) the while loop will stuck indefinitely.

I know this script is meant for big files which would always contain at least several lines, but it would be clever to make the script error-proof.

Thus, here's a little modification to his code.

<?php
function readLastLine ($file) {
  
$fp = @fopen($file, "r");

  
$pos = -1;
  
$t = " ";
   while (
$t != "\n") {
       if (!
fseek($fp, $pos, SEEK_END)) { // *** - fseek returns 0 if successfull, and -1 if it has no succes as in seeking a byte outside the file's range
          
$t = fgetc($fp);
          
$pos = $pos - 1;
       } else {
// ***
          
rewind($fp); // ***
          
break; // ***
      
} // ***
  
}
  
$t = fgets($fp);
  
fclose($fp);
   return
$t;
}
?>

Lines added and/or modified have been marked with "// ***". I hope this helps!

Regards!
mail at ulf-kosack dot de
27-May-2006 10:44
Here a little extension for the code of ekow.
If you want to read more than one line and more than one file. Some times the last five ore ten lines are interesting in.

You only have to submit a array with filenames and optionally a number of lines you want to read.

<?php
 
function read_logfiles($files, $lines=5)
  {
   foreach(
$files as $file_num => $file) {
     if (
file_exists ($file) ) {
      
$handle = fopen($file, "r");
      
$linecounter = $lines;
      
$pos = -2;
      
$t = " "
      
$text[$file_num] = "";
       while (
$linecounter > 0) {
         while (
$t != "\n") {
          
fseek($handle, $pos, SEEK_END);
          
$t = fgetc($handle);
          
$pos --;
         }
        
$t = " ";
        
$text[$file_num] .= fgets($handle);
        
$linecounter --;
       }
      
fclose ($handle);
     } else {
      
$text[$file_num] = "The file doesn't exist.";
     }
   }
  
   return
$text;
?>
ekow[at]te.ugm.ac.id
11-Dec-2005 05:22
A little correction for code to read last line from chenganeyou at eyou dot com.
$linenumber = sizeof($file)-1;
should be
$linenumber = sizeof($contents)-1;
because sizeof will count array element, not file size.
<?php
function readlastline($file)
{
      
$linecontent = " ";
      
$contents = file($file);
      
$linenumber = sizeof($contents)-1;
      
$linecontet = $contents[$linenumber];
       unset(
$contents,$linenumber);
       return
$linecontent;
}
?>
jeffunk7 at yahoo dot com
09-Dec-2005 06:46
If you, like me, need the second to last line from a text file (or some other line near the end that you will know the number of, ie the fourth to last line) then this addition to Jim's code can help you.

//$linefromlast is the linenumber that you need, the last line being 1, the second to last being 2, and so on...

function readlog($file, $linefromlast){
   $fp = @fopen($file, "r");
   $pos = -2;
   $t = " ";
   $linecounter = 1;
       while ($t != "\n" and $linecounter<=$linefromlast) {
               fseek($fp, $pos, SEEK_END);
               $t = fgetc($fp);
               $pos = $pos - 1;
               if ($t == "\n" and $linecounter < $linefromlast) {
                       fseek($fp, $pos, SEEK_END);
                       $t = fgetc($fp);
                       $pos = $pos - 1;
                       $linecounter = $linecounter +1;
               }
         }
   $t = fgets($fp);
   fclose($fp);
   return $t;
}
memphis
22-Jul-2005 01:41
Actually chenganeyou, your function causes the entire file to be read into an array, and then you look at the last element of the array.  While this works fine for a small file, an sizeable file is going to suck down memory and time.  Using a 15 MB file your function took around 2 secs to return.

The function provided by Jim goes directly to the end of the file and only reads in that line.  I had to set the offset ($pos) to -2 for it to work in my case however.  Using the same 15 MB file this function returns immediately.
chenganeyou at eyou dot com
27-Jun-2005 01:35
I use the following codes to read the last line of a file.
Compared to jim at lfchosting dot com, it should be more efficient.

<?php
function readlastline($file)
{
      
$linecontent = " ";
      
$contents = file($file);
      
$linenumber = sizeof($file)-1;
      
$linecontet = $contents[$linenumber];
       unset(
$contents,$linenumber);
       return
$linecontent;
}
?>
phil at NOSPAM dot blisswebhosting dot com
25-May-2005 08:43
In order to read a text file from end->beginning e.g display the most recent contents of a log file first.  I use the following.

It basically just uses fseek to find the end of the file, ftell to find the byte count for a counter, then iterates backwards through the file using fgetc to test for the newline charater.

$i=0 ;
$lines=500 ;
$fp = fopen($log,"r") ;
if(is_resource($fp)){
   fseek($fp,0,SEEK_END) ;
   $a = ftell($fp) ;
   while($i <= $lines){
       if(fgetc($fp) == "\n"){
           echo (fgets($fp));
           $i++ ;
       }
   fseek($fp,$a) ;
   $a-- ;
   }
}
alan at peaceconstitution.com
17-May-2005 06:03
Thanks to Dan, whose above comment provided a key to solve the issue of how to append to a file.
     After, using phpinfo(); I made sure my installation of PHP had the requisite settings mentioned in the text to the manual entry for fopen(), I was puzzled as to why my use of fopen() with the append option 'a' (append option) didn't work. Then I  read a comment contributed to Appendix L (http://us2.php.net/manual/en/wrappers.php) that the append option 'a' for fopen() doesn't work as expected. The writer suggested using the 'w' option instead, which I found did work. But the 'w' option (write option) overwrites everything in the file.
     The question remained how to accomplish appending. Following Dan's suggestion about the 'r+' option, I tried this, which works fine:
       $string = "Message to write to log";
       $filehandle = fopen ("/home/name/sqllogs/phpsqlerr.txt", 'r+');
   fseek ( $filehandle,0, SEEK_END);
   fwrite ( $filehandle, $string."\n" );
   fclose ($filehandle);
Lutz ( l_broedel at gmx dot net )
14-Feb-2005 02:25
Based on the function below, provided by info at o08 dot com (thanks), the following should enable you to read a single line from a file, identified by the line number (starting with 1):

<?
  
function readLine ($linenum,$fh) {
      
$line = fgets ($fh, 4096);
      
$pos = -1;
      
$i = 0;

       while (!
feof($fh) && $i<($linenum-1)) {
          
$char = fgetc($fh);
           if (
$char != "\n" && $char != "\r") {
              
fseek($fh, $pos, SEEK_SET);
              
$pos ++;
           }
           else
$i ++;
       }
      
$line = fgets($fh);
       return
$line;
   }
//readLine()
?>
info at o08 dot com
15-Feb-2004 11:27
I think the function should be as following to deal any combination of cr & lf, no matter the line ends by cr, lf, cr-lf or lf-cr:

<?php
function getline ($handle) {
       while (!
feof($handle)) {
          
$char = fgetc($handle);
           if ((
$char == "\n") or ($char == "\r")) {
              
$char2 = fgetc($handle);
               if ((
$char2 != "\n") && ($char2 != "\r")) {
                  
fseek ($handle,-1,SEEK_CUR);
               }
               break;
           }
           else {
              
$buffer .= $char;
           }
       }
       return
$buffer;
}
?>
jim at lfchosting dot com
04-Nov-2003 06:03
Here is a function that returns the last line of a file.  This should be quicker than reading the whole file till you get to the last line.  If you want to speed it up a bit, you can set the $pos = some number that is just greater than the line length.  The files I was dealing with were various lengths, so this worked for me.

<?php
function readlastline($file)
{
      
$fp = @fopen($file, "r");
      
$pos = -1;
      
$t = " ";
       while (
$t != "\n") {
            
fseek($fp, $pos, SEEK_END);
            
$t = fgetc($fp);
            
$pos = $pos - 1;
       }
      
$t = fgets($fp);
      
fclose($fp);
       return
$t;
}
?>
aspyrine at hotmail dot com
11-Mar-2003 07:51
If you want to go to the end of a socket stream with fseek() you'll get the following error :
"stream does not support seeking"

feof() wont work eiver in a stream (ie. smtp)

You can move the pointer to the end with this command :
while(fgetc($fp)) {}
...so easy :-)
16-Sep-2002 01:25
Don't use filesize() on files that may be accessed and updated by parallel processes or threads (as the filesize() return value is maintained in a cache).
Instead lock the opened file and use fseek($fp,0,SEEK_END) and ftell($fp) to get the actual filesize if you need to perform a fread() call to read the whole file...
24-Aug-2002 05:12
The following call moves to the end of file (i.e. just after the last byte of the file):

    fseek($fp, 0, SEEK_END);

It can be used to tell the size of an opened file when the file name is unknown and can't be used with the filesize() function:

    fseek($fp, 0, SEEK_END);
    $filesize = ftell($fp);

The following call moves to the begining of file:

    fseek($fp, 0, SEEK_SET);

It is equivalent to:

    rewind($fp);
dan at daniellampert dot com
01-Jan-2002 02:54
For all first-time users of the fseek() function, remember these three things:

1. to use a programming expression, fseek() is "base 0", so to prepare the file for writing at character 1, you'd say fseek($fp,0); and to prepare the file for writing at character $num, you'd say fseek($fp,($num-1));

2. here's the formula for accessing fixed-length records in a file (you need to seek the position of the end of the previous record):

  /* assumes the desired record number is in $rec_num */
  /* assumes the record length is in $rec_len */
  $pos = ( ($rec_num-1) * $rec_len );
  fseek($fp,$pos);

3. if you're using fseek() to write data to a file, remember to open the file in "r+" mode, example:

  $fp=fopen($filename,"r+");

Don't open the file in mode "a" (for append), because it puts the file pointer at the end of the file and doesn't let you fseek earlier positions in the file (it didn't for me!). Also, don't open the file in mode "w" -- although this puts you at the beginning of the file -- because it wipes out all data in the file.

Hope this helps.

Citas célebres

La fuente de toda poesía es el sentimiento profundo de lo inexpresable.

Lucien Arréat
Filósofo francés
(1841-1922)
Citas en tu mail
©Contenidos Gratis

Ilusiones Opticas
ilusion_optica_045.jpg
Contenidos Web

Chiste de... Mamá, mamá
Marcianitos

- Papá, papá, ¿los marcianos son amigos o enemigos?

- ¿Por qué?

- Porque vino una nave y se llevó a la abuela.

- ...entonces son amigos.
Chistes en tu mail
©ContenidosGratis

Humor Gráfico
humor_grafico_010.jpg
Contenidos Web

Inicio | Acción | Estrategia | Palabras | Puzzles | Solitarios | Foro Trucos
Cake ManiaCake Mania
Jugadores: 6835
Categoría del juego: Acción
Objetivo del juego: Ayuda a Jill a recuperar la pastelería de su abuela llevando su propia pastelería; consigue clientes y gana dinero.
Rainbow WebRainbow Web
Jugadores: 2199
Categoría del juego: Puzzles
Objetivo del juego: Rompe un pegajoso hechizo y salva un reino de fantasía en Rainbow Web. Tendrás toneladas de diversión mientras juegas a este mágico desafío para la mente.
Mahjongg FortunaMahjongg Fortuna
Jugadores: 12462
Categoría del juego: Solitarios
Objetivo del juego: Velocidad y habilidad mental son las armas más importantes en esta versión de un antiguo juego asiático. Despeja el tablero lo antes posible haciendo clic en las fichas iguales y gánate la fama eterna de la puntuación más alta.
Chainz 2Chainz 2
Jugadores: 6955
Categoría del juego: Puzzles
Objetivo del juego: Entra en el mundo de las combinaciones con Chainz 2: Relinked, emocionante secuela del exitazo del año pasado, Chainz. Gira eslabones y crea combinaciones de 3 ó más.
DeliciousDelicious
Jugadores: 4405
Categoría del juego: Acción
Objetivo del juego: ¿Eres un as de la multitarea? ¿Quieres que tus clientes estén contentos? ¡Pues Delicious es tu juego! Sacia el apetito de los clientes y tenlos contentos; ¡no te arriesgues!
BookwormBookworm
Jugadores: 4568
Categoría del juego: Palabras
Objetivo del juego: Junta las letras para formar palabras. ¡Las palabras más largas valen más puntos!
ZumaZuma
Jugadores: 4976
Categoría del juego: Acción
Objetivo del juego: Controla el ídolo de la rana de piedra de los antiguos Zuma en este intrigante enigma de acción. ¡Dispara bolas para formar conjuntos de tres, pero si dejas que lleguen a la calavera dorada morirás!
Jewel of AtlantisJewel of Atlantis
Jugadores: 3798
Categoría del juego: Puzzles
Objetivo del juego: Descubre la ciudad hundida de la Atlántida y busca valiosos tesoros. Viaja más allá de las profundidades del mar y vive trepidantes aventuras en Jewel of Atlantis.
Jewel QuestJewel Quest
Jugadores: 3727
Categoría del juego: Puzzles
Objetivo del juego: Convierte la arena de la antigua selva en oro tan rápido como puedas juntando grupos de 3 elementos. ¡Los grupos más grandes valen más puntos!
Bejeweled 2Bejeweled 2
Jugadores: 3659
Categoría del juego: Puzzles
Objetivo del juego: Con cuatro modos de juego únicos y fascinantes, nuevas piezas de juego explosivas e imponentes fondos planetarios, Bejeweled 2 es mucho más adictivo que nunca.
Contenidos gratis en tu webSiguiente >>

Fotos divertidas
fotos_increibles_0330.jpg
Contenidos Web
microrobots avion deportes riesgo recetas cocina canaria juegos online gratis moto motociclismo horoscopos naranjas valencianas surf canarias montañismo ciudades turismo postales gratis library Horoscopos Diarios Windsurf Canarias
fregadero microondas placa electrica bañopreparar camper pantalla plananevera compresor electricacamper fiat ducato camper baño quimicomampara enrollable bañocamper aire climatizadofurgoneta surf windsurffurgoneta surf windsurftelevisor furgonetas camperfurgonetas camper cama

Sudoku del día
Nivel de dificultad: Fácil



Cómo jugar:
El juego consiste en colocar los números del 1 al nueve de tal forma que no se repita el mismo número en la columna, fila y caja (bloques 3x3 enmarcados).

©Contenidos Gratis | Sudoku en tu mail
Sucedió el...

30 de agosto de 1617

Fallece Santa Rosa de Lima, por la que se celebra el "Día de la Patrona de América".
Efemérides en tu mail
©Contenidos Gratis
windsurf canarias youtube porno canarias baleares valencia madrid fallera mayor campus party alcacer feria valencia fernando alonso loterias dinero inversiones violencia de genero makro empresas cartera soledad tolerancia metro valencia gobierno de españa violencia de genero UIMP navidad