Allegro.cc - Online Community

Allegro.cc Forums » Programming Questions » to dumb to read a string

Credits go to Arthur Kalliokoski and Trent Gamblin for helping out!
This thread is locked; no one can reply to it. rss feed Print
to dumb to read a string
knudel
Member #13,235
August 2011

Hi,

my problem is that I've got a file in which I've written a string and two integers and I'm trying to read them with this function:

#SelectExpand
1void read(char* path){ 2 file=al_fopen(path,"r"); 3 4 char str[256]; 5 int mapx, mapy; 6 7 //string 8 int i=-1; 9 do{ 10 i++; 11 al_fread(file,&str[i],sizeof(char)); 12 }while(str[i]!='\0'); 13 14 //2 integers 15 al_fread(file,&mapx,sizeof(int)); 16 al_fread(file,&mapy,sizeof(int)); 17 18 al_fclose(file); 19}

but it seems that my solution to read a string takes one byte more from the file as it should and so my string is "tiles1.bmpd" instead of "tiles1.bmp" and the following ints have the values 6553600 and 0 instead of 100 and 100.

Does anyone have a better solution for reading strings?

thanks for all answers :)

Arthur Kalliokoski
Second in Command
February 2005
avatar

Let me get this straight, the file has a null terminated string followed immediately by two binary integers? The ints aren't in ASCII?

They all watch too much MSNBC... they get ideas.

Trent Gamblin
Member #261
April 2000
avatar

I think I'm thinking along the same lines as Arthur. My guess is you didn't null terminate, or you had \n in the file before the 0.

knudel
Member #13,235
August 2011

Damn, I'm sorry.
I used al_fwrite(file,string,strlen(string)) and not al_fwrite(file,string,strlen(string)+1) to write the string in the file so the '\0'-charakter was missing.

Thanks for the hint :)

Trent Gamblin
Member #261
April 2000
avatar

Just so you know, read ints from a file 4 bytes at a time with fread isn't portable. Allegro has functions such as al_fread32le for this purpose.

knudel
Member #13,235
August 2011

thanks :D
So al_fread32le would work on all platforms correct?

Trent Gamblin
Member #261
April 2000
avatar

If you use that and write32le every time on all platforms then it will work.

Go to: