Jump to content
  • Advertisement

Archived

This topic is now archived and is closed to further replies.

HolyFish

How can I save integers to a file ???

This topic is 5838 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi, I can save strings and characters to a file, but when I want to save integers and I look in my file then there are just symbols and rubbish and no integers...need some help... This is how I save : //////////////////////////////////// FILE *MyFile; char Test[100] void main () { strcpy(Test, "This is my test sentence"); if((MyFile=fopen("Test.txt", "w") != NULL)) { fwrite(Test, sizeof(char), strlen(Test), MyFile); fclose(MyFile); } } -> This works...BUT : /////////////////////////////////////////////// FILE *MyFile; int Test[5] = {1,2,3,4,5}; void main () { if((MyFile=fopen("Test.txt", "w") != NULL)) { fwrite(Test, sizeof(int), 5, MyFile); fclose(MyFile); } } -> This doesn''t work, what am I doing wrong ?? Are there more possibilities to save data to a file ?? Thanks,

Share this post


Link to post
Share on other sites
Advertisement
You are saving integers as integers (internal format) to a file, but then apparently expect them to be in the file in a string representation.

In order order to see them as strings, you must convert the ints to strings prior to or as you save.

Not that your code is ok, but I might assume that writing the equivalent read routine on your gobbledygook file as is would retrieve the integers stored therein, regardless of how they look in the file by eye.

Personally I sprintf all my output to a string, then just output the string whole (I do this so that chunk of data can be written to the file, console, screen, etc, I do very little formatting on the fly in a fwrite). for example:

int test[5]={1,2,3,4,5};
char s[80];

sprintf(s,"%d %d %d %d %d\n",test[0],test[1],test[2],test[3],test[4],test[5]);
// write s to file.
file << s; // c++

zin

zintel.com - 3d graphics & more or less

Share this post


Link to post
Share on other sites

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!