SitePoint Sponsor

User Tag List

Results 1 to 5 of 5

Thread: For feof()?

  1. #1
    SitePoint Zealot
    Join Date
    Oct 2008
    Posts
    155
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    For feof()?

    Can a for loop be done with feop()?

  2. #2
    SitePoint Evangelist
    Join Date
    Jun 2006
    Location
    Wigan, Lancashire. UK
    Posts
    523
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Not a for loop, but
    PHP Code:
    $fh fopen('myFile.txt','r');
    $fileContent '';
    while (!
    feof($fh)) {
       
    $fileContent .= fread($fh,1024);
    }
    fclose($fh); 
    ---
    Development Projects:
    PHPExcel
    PHPPowerPoint

  3. #3
    SitePoint Zealot
    Join Date
    Oct 2008
    Posts
    155
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Maybe there is a better way for me to do this. What I am trying to do is the following:

    1) Read a file using fopen
    2) I need to be able to skip the first 2 lines and the last 2 lines

    My current method is the same as you have posted above but I am not able to skip the first 2 lines and the last 2. Is there any way I can achieve this with the method that you posted?

    EDIT: I am staying away from count(file("text.txt")) because the files I am dealing with have about 900,000 lines.

  4. #4
    SitePoint Wizard gRoberts's Avatar
    Join Date
    Oct 2004
    Location
    Birtley, UK
    Posts
    2,439
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Sounds silly but could you not explode the text into an array of lines, remove the 4 lines and then implode it (if required)?

    edit: With the loop, you'll need to count the lines, thus you'd always have to use count(file("text.txt")) to find out how many lines there are so you know when to remove the last two. Shifting and popping the first and last two lines would seem the only easy way to do it.


  5. #5
    SitePoint Evangelist
    Join Date
    Jun 2006
    Location
    Wigan, Lancashire. UK
    Posts
    523
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    fread() doesn't actually read a line at a time anyway, but fgets can read a line at a time. Slightly quirky, but you can easily discard the first two lines:
    PHP Code:
    $fh fopen('myFile.txt','r');
    $discard fgets($fh);
    $discard fgets($fh); 
    Then read the next two lines into an array:
    PHP Code:
    $fileArray[] = fgets($fh);
    $fileArray[] = fgets($fh); 
    Then loop till feof(), actually reading the next line, but processing the first in the array before unshifting it when you've finished with it.
    PHP Code:
    while (!feof($fh)) {
       
    $fileArray[] = fgets($fh);
       
    processLine(array_shift($fileArray));

    ---
    Development Projects:
    PHPExcel
    PHPPowerPoint


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •