Friday, July 31, 2009

How retain the data in a variable in C programming( not C++) after closing the program???

Iam trying to make a information system using C, not C++ but i want to save the changes done when i open my program and close it and when i open again it does'nt go back to the original but the retains the changes done.


Meaning A was originally 1 but when i run the program i changed A into 3 and when i close the program and then open again i want A to be 3 not 1.


Can anyone help cause i cant seem to understand the tutorials in the internet.


tnx :)

How retain the data in a variable in C programming( not C++) after closing the program???
Store the data in a file. When the program starts up, read the values from the file. When the program ends, write the new values to the file.





Suppose you want variables a, b, and c... (double-check my syntax)








FILE *iniFile;





/* Open the file and read in the values */


if ( (iniFile = fopen("mydata.ini","r"))==NULL) {


printf("Unable to open file for read!\n");


exit 1;


}





/* Read in the values */


if ( fscanf(iniFile, "%d %d %d", %26amp;a, %26amp;b, %26amp;c) != 3 ) {


printf("Error - not enough values on ini file\n");


}


fclose();








/* Write out new values -


NOTE: this wipes out previous values */


if ( (iniFile = fopen("mydata.ini","w"))==NULL) {


printf("Unable to open file for write!\n");


exit 1;


}





/* Write out the values */


if ( ! fprintf(iniFile, "%d %d %d", %26amp;a, %26amp;b, %26amp;c) ) {


printf("Error - unable to write file\n");


}


fclose();
Reply:When you close the program just save any variable or change or whatever in an external file (such as a*.cfg file or what you like the most).


No comments:

Post a Comment