Page 1 of 1

Why fgetc() can not read out the right value in my code ?

Posted: Thu Oct 24, 2002 10:19 am
by weilich
I am new in PHP. I am trying to convert a CGI/C code to PHP code as below. Both codes are running in the same directory on a Unix server, reading the same file "rgb.dat". The CGI code works fine, the PHP does not work. Problem is the $low and $high get the wrong values by using the fgetc($fp). But the $buf get the right value using the fread() function.
Does the fgetc function in C and PHP work in the same way? I am really confused about that. Please help. Many thanks!


//******** C code *********
seed=12;
fp=fopen("rgb.dat","rb");
fseek(fp,50*seed,SEEK_SET);
fread(buf,26,1,fp);
fseek(fp,50*seed+26,SEEK_SET);
for (i=0;i<12;i++)
{
int low, high;
low =fgetc(fp);
high =fgetc(fp);
N[i]=low+high*100;

}

//****** PHP code ***********
$seed =12;
$fp=fopen("rgb.dat","rb");
fseek($fp,50*$seed,SEEK_SET);
$buf=fread($fp, 26);
fseek($fp,50*$seed+26,SEEK_SET);
for ($i=0;$i<12;$i++)
{
$low =fgetc($fp);
$high =fgetc($fp);
$N[i]=low+high*100;

}

Posted: Thu Oct 24, 2002 11:45 am
by volka
typo?
$N=low+high*100;
should be

Code: Select all

$N&#1111;i]=$low+$high*100;

Posted: Thu Oct 24, 2002 12:50 pm
by weilich
That is just the typo mistake in my last message, my PHP code running on the server does not have that type mistake. And the problem actually start at the line $low=fgetc($fp); It can not read in the right value from the file as my CGI code did. Anyway, thanks for your help.

Posted: Thu Oct 24, 2002 1:47 pm
by rev
My guess would be that fseek() is failing for some reason... test it to see if it's proving true or false...

Code: Select all

&lt;?php
if(fseek($fp,(50*$seed),SEEK_SET)) echo "true"; else echo "false";
?&gt;
Why it's failing, not exactly certain per not knowing the contents of your DAT file. But if it's working per the C code, I would imagine it's the way the file is being read by PHP.

Posted: Thu Oct 24, 2002 2:33 pm
by volka
C's fgetc returns an integer, PHP's fgetc a string. Implicit typecasting will not take a string's character values but (if typecastes to a numeric value) tries to interpret the string as number (like '34' or '12.5' ...).
Try the ord function

Posted: Thu Oct 24, 2002 3:58 pm
by weilich
Thanks a lot, volka. The ord() function solve my problem.

[quote="volka"][url=http://netbsd.gw.com/cgi-bin/man-cgi?fgetc+3]C's fgetc[/url] returns an integer, [url=http://www.php.net/manual/en/function.fgetc.php]PHP's fgetc[/url] a string. Implicit typecasting will not take a string's character values but (if typecastes to a numeric value) tries to interpret the string as number (like '34' or '12.5' ...).
Try the [url=http://www.php.net/manual/en/function.ord.php]ord function[/url][/quote]