to dumb to read a string


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:

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

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

Trent Gamblin

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.


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

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.


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

Trent Gamblin

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

Thread #608504. Printed from