• ### Announcements

#### Archived

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

# Tutorials on text files

## 4 posts in this topic

Could anyone gimme a link to tutorials on loading from and writing to plain text files ? Or if there is a better way to save info so that i wont loose it if i quit my prog. Actually, i only have to save numbers.. but saving characters might be useful too if that doesnt complicate things too much. JT
0

##### Share on other sites

first start opening a file:
FILE * file = fopen("save.txt", "wt");
"wt" stands for write textmode....
now you''ve got a handle to an open file...

I guess you know the printf(); function and it''s syntax...
the same with a f in front of it and a little diffrent syntax:

fprintf(file, "%f %d %s\n", 1.875, 16, raw);

and finally close the file:

fclose (file);

this would result in following .txt file

1.87500 16 raw

(how do I show a newline charakter? :p)

FILE * file = fopen("save.txt", "rt");

float afloat;
int anint;
char astring[50];

fscanf(file, "%f %d %s", &afloat, &anint, astring);

watchout that strings in the file may not have spaces if you''re trying to read it with one %s..

ok, hope that helped,
cya,
Phil

Visit Rarebyte!
and no!, there are NO kangaroos in Austria (I got this questions a few times over in the states
0

##### Share on other sites
yup, that helped
thanks alot.

btw, check out the project im workin on: http://home.online.no/~7396/delta/
0

##### Share on other sites
If you''re saving numbers, you''d be far better off with binary files. You can save numbers and any other variables/structs/whatever like this:

  int SaveFile(char *filename){ FILE *file; //Open file (w stands for write). Return 0 on error if((file = fopen(filename, "w")) == NULL) return 0; //Write the integers to the file fwrite(&SOME_DATA, sizeof(int), 1, file); fwrite(&some_more_data, sizeof(int), 1, file); //Close file fclose(file);}int OpenFile(char *filename){ FILE *file; //Open file (r stands for read). Return 0 on error if((file = fopen(filename, "r")) == NULL) return 0; //Read integers from file fread(&some_data, sizeof(int), 1, file); fread(&some_more_data, sizeof(int), 1, file); //Close file fclose(file);}

That should do it. Saving in binary mode also means it will be harder for your users to manually modify their save files to cheat.
0

##### Share on other sites
Jup, he''s right, I just think text files are easier to start with :o)... you can also use nice tricks... like encoding your numbers in some fashion.. that makes things harder too :o)))

cya,
Phil

Visit Rarebyte!
and no!, there are NO kangaroos in Austria (I got this questions a few times over in the states
0