/    Sign up×
Community /Pin to ProfileBookmark

hi

i have a loop where i read values line by line from file
something like:

[code=php]
while(!feof($fp))
{
$l=fgets($fp);
echo($l);
}
[php]
i noticed that when i read ordinary ascii file feof() ends the loop as it should but when i read utf-8 file, the loop does additinal iteration so i read some garbage and get errors and warning…

so for reading unicode files without errors i use this loop:
(i’m assuming filesize()>0)
[code=php]
do
{
$l=fgets($fp);
if(feof($fp))
break;
echo($l);
}while(!feof($fp));
[php]
and then it works fine…

Is it some known issue?

to post a comment
PHP

4 Comments(s)

Copy linkTweet thisAlerts:
@ShrineDesignsDec 06.2004 — there are some disadvantages for using feof(), it uses good amount of memory, which can bog a server down

also you are not doing any sort processing on the data retrived from the file so it is not nessacary to use feof()[code=php]<?php
while(($line = fgets($fp)) !== false)
{
echo $line;
}
?>[/code]
or[code=php]<?php
echo fgets($fp, filesize($file));
?>[/code]
Copy linkTweet thisAlerts:
@pti4kaauthorDec 06.2004 — i posted simplified loop...ofcourse i do some proccessing

if there is another way for testing file end please tell me...

after little testing now i know this:

what really matters is when eof() returns "true"...

example: reading file line by line and doing some proccessing:

this loop
[code=php]
while(!feof($fp))
{
$l=fgets($fp);
$data=explode(',',$l);
$l[0]+=1;
$l[1]+=4;
}
[/code]


is wrong because feof() will return true [B]only after there was an attemt to read afer file end[/B]...

so what this basicly means is that the last line will read EOF character or some other "garbage" and then script will attemt to proccess that and obviously will crash...
Copy linkTweet thisAlerts:
@ShrineDesignsDec 06.2004 — give this a try:[code=php]<?php
$size = filesize('/path/to/file.txt');

while(ftell($fp) < $size)
{
$line = fgets($fp);
// ...
}
?>[/code]
Copy linkTweet thisAlerts:
@pti4kaauthorDec 06.2004 — ok

i thought about using ftell but i'm not sure how safe it is to use filesize because the file system can be compressed.
×

Success!

Help @pti4ka spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.18,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...