Binary Storing Data in Itself
Posted: Fri Jul 18, 2008 5:12 pm
This is technically a question about C rather than a client-specific question...
If I want to write a programme that stores some data in its own binary rather than an external file, how do I go about it?
Here is an example of a programme, my mume-time offline reference:
I would like the resulting binary to store the reference in itself rather than in the external timestorage.data.
(Optimisation suggestions for the current time calculation in mclockGet () are also welcome.)
If I want to write a programme that stores some data in its own binary rather than an external file, how do I go about it?
Here is an example of a programme, my mume-time offline reference:
Code: Select all
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <stdlib.h>
int oldSysTime, newSysTime, timeDiff;
int tMonth, tDay, tHour, tMin;
FILE *storage;
void error(void)
{
printf ("#print (\"Clock error! Try giving HELP as argument.\")\n");
exit (1);
}
void mclockHelp(void)
{
exit (0);
}
void mclockGet(void) {
if ((storage = fopen ("/home/mikaels/mud/powwow-1.2.13/scripts/timestorage.data", "r+")) == NULL) {
printf ("#print (\"Error: could not open scripts/timestorage.data for reading!\")\n");
exit (1);
}
fscanf (storage, "%d %d %d %d %d", &oldSysTime, &tMonth, &tDay, &tHour, &tMin);
fclose (storage);
timeDiff = newSysTime - oldSysTime;
tMin += timeDiff;
while (tMin > 59) {
tMin -= 60;
tHour++;
}
while (tHour > 23) {
tHour -= 24;
tDay++;
}
while (tDay > 30) {
tDay -= 30;
tMonth++;
}
if (tMonth > 12) tMonth %= 12;
printf ("#(@timeMonth=%d, @timeDay=%d, @timeHr=%d, @timeMi=%d);clock;#in clockTimer (800) clockIncrease\n", tMonth, tDay, tHour, tMin);
exit (0);
}
void mclockStore(char* arg2, char* arg3, char* arg4, char* arg5) {
if ((tMonth = atoi (arg2)) > 12) error();
if ((tDay = atoi (arg3)) > 30) error();
if ((tHour = atoi (arg4)) > 23) error();
if ((tMin = atoi (arg5)) > 59) error();
if ((storage = fopen ("scripts/timestorage.data", "w")) == NULL) {
printf ("#print (\"Error: could not open scripts/timestorage.data for writing!\")\n");
exit (1);
}
fprintf (storage, "%d %d %d %d %d", newSysTime, tMonth, tDay, tHour, tMin);
fclose (storage);
exit (0);
}
int main (int argc, char* argv[]) {
if (argc < 1) error();
newSysTime = time (NULL);
if (strcmp (argv[1], "HELP") == 0) mclockHelp();
if (strcmp (argv[1], "GET") == 0) mclockGet();
if (strcmp (argv[1], "STORE") == 0) {
if (argc != 6) error();
mclockStore(argv[2], argv[3], argv[4], argv[5]);
}
error();
return 0;
}
(Optimisation suggestions for the current time calculation in mclockGet () are also welcome.)