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;
}
Why fgetc() can not read out the right value in my code ?
Moderator: General Moderators
typo?
should be$N=low+high*100;
Code: Select all
$Nїi]=$low+$high*100;My guess would be that fseek() is failing for some reason... test it to see if it's proving true or false...
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.
Code: Select all
<?php
if(fseek($fp,(50*$seed),SEEK_SET)) echo "true"; else echo "false";
?>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
Try the ord function
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]
[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]