🎉 Celebrating 25 Years of GameDev.net! 🎉

Not many can claim 25 years on the Internet! Join us in celebrating this milestone. Learn more about our history, and thank you for being a part of our community!

reading/writing data

Started by
1 comment, last by xSuiCidEx 24 years, 7 months ago
If this is what you're getting when you look at the file, could it be something to do with the fact that you're using "wb" in the fopen function. This stands for write bytes, "wt" stands for write text.

However...I just re-read your code and you're not actually writing out the strings, you're writing out the structure, which contains char*'s, which _point_ to your text, but using fwrite won't write it to file. It'll probably just write the pointer addresses, which isn't what you want at all.
Try using fprintf instead or convert the char* to char[256].

[This message has been edited by MikeD (edited November 11, 1999).]

Advertisement
i have been working on a tile based game and i have been having troubles with writing/reading data. this is what i got:

struct MAPINFO{
char *MapName;
char *MapCreator;
char *MapDescription;
int Version;
int Background;
int Width;
int Height;
};

MAPINFO MapInfo;

and this is what/how i want to write to the file:

MapInfo.MapName = "name";
MapInfo.MapCreator = "creator";
MapInfo.MapDescription = "short description";
MapInfo.Version = 7;
MapInfo.Background = 1;
MapInfo.Width = 255;
MapInfo.Height = 255;
FILE *fh;
fh = fopen("write.txt", "wb");
fwrite(&MapInfo, sizeof(MapInfo), 1, fh);
fclose(fh);

this seems to all work fine...it writes the version, background, width and height as characters in the text file...(ex. instead of it writing "7" (version) it writes ""...which isn't a problem at all...except it doesn't write the mapname, mapcreator, or mapdescription correctly or at all for that matter...this is what i get from it:

"`SA hSA pSA d d "

im kinda lost....if anyone can tell me wuts going on...it would help alot...thanx

brad

---===xxxx===---
----THE END----
---===xxxx===---
I would certainly say this is due to binary storage. When you tell it to fwrite the structure, it is simply writing the memory allocated to the structure to disk. The 7 in the version field is represented as ASCII 7 (a control character) instead of '7', which is ASCII 55. And the pointers are being stored, rather than the actual character data. Since your structure contains pointers, you cannot simply fwrite it to disk. Instead, first write the strings on seperate lines like the following:

fwrite(MapInfo.MapName, strlen(MapInfo.MapName), 1, fh);

Then, write from the Version element on down, like the following:

fwrite(&(MapInfo.Version), sizeof(int)*4, 1, fh);

- Splat

This topic is closed to new replies.

Advertisement