Reply to Re: Line count/blank line issue with file(), etc.

Your name:

Reply:


Posted by Curtis on 12/28/05 01:43

Sean <oreilly.sean@gmail.com> wrote in message
news:1135699277.506193.293080@g47g2000cwa.googlegroups.com..
..
> If you have a text file.
>
> file://numbers.txt
> 1
> 2
> 3
>
> 5
> 6
> 7
>
> The resulting array (i.e. print_r(file('numbers.txt')); (
>
> is
>
> Array
> (
> [0] => 1
>
> [1] => 2
>
> [2] => 3
>
> [3] =>
>
> [4] => 5
>
> [5] => 6
>
> [6] => 7
> )
>
> which is what I would expect. Nothing so extraordinary
about that.

But that wasn't the issue, Sean. The issue is where your 0-3
is in file A and 5-7 in file B. It's the newline AT THE END
of a file which seems to go missing.

The file() function seems to be losing the last newline
character (0a). If your 0-3 were in a file and read by
file(), the line count would be three and not four. (This is
for PHP 4.2.something)

I read in the PHP docs that fgets() is a lot faster. I
experimented with fgets() this morning, and the line count
seems correct for that function.

> New line or carriage return or whatever is still just a
character (or
> two characters if you use windows), and the manual spells
out quite
> clearly what happens.
>
> "Note: Each line in the resulting array will include the
line
> ending, so you still need to use rtrim() if you do not
want the line
> ending present."

Unfortunately, that appears to disagree with my results for
file(). It is true for all new line characters except the
last one. In other words

1 line a
2 line b
3 line c
4 <-- new line only
5 <-- new line only
6 <-- new line only

will return FIVE from file() with count().

fgets() seems to return the correct count, SIX, used like
so.

function fileg($filename)
{
$fd = fopen ($filename, "r");
while (!feof ($fd))
{
$buffer = fgets($fd, 4096);
$lines[] = $buffer;
}
fclose ($fd);
return $lines;
}

--

Curtis

Visit We the Thinking
www.wethethinking.com
An online magazine/forum
devoted to philosophical
thought.

[Back to original message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация