I'm coding a net开发者_JAVA技巧work game in C. I 've written scores in a file. I also wanted to add the date of the day. Here is the file's structure : Date Name Score and the code :
ScoreFile = fopen("scores.txt", "a");
fprintf(ScoreFile, "%s %d\n", Name, Score);
I've tried system("date") but it's printed on stdout. I think that I can't add the Date with fprintf.
Do you know a solution that permits to add Date in a file ? (maybe something from time.h ?)
thanks a lot !!
Consider using strftime to convert the time structure to string.
Example (from link above):
#include <time.h>
// ...
char s[30];
size_t i;
struct tm tim;
time_t now;
now = time(NULL);
tim = *(localtime(&now));
i = strftime(s,30,"%b %d, %Y; %H:%M:%S\n",&tim);
puts Jul 9, 2011; 17:55:55\n
in s
Something like this should work
time_t now;
time(&now);
printf("... %s\n", ctime(&now));
If you need to specify your own format, look into strftime
. If you later need to read it back and parse it, you might be better off writing the number of seconds since epoch (the time_t
, perhaps in ASCII?).
The simplest would be to:
time_t now = time(NULL);
fprintf(ScoreFile, "[%s] %s %d\n", ctime(&now), Name, Score);
Have a look at strptime, strftime and mktime from time.h.
To parse:
struct tm timeStruct = {0,0,0,0,0,0,0,0,0};
char *timeBuf = "03061983";
char *p = strptime(timeBuf, "%d%b%y", &timeStruct);
if (p != NULL)
{
// manipulate timeStruct.
// use mktime to get the time_t value
}
To write:
time_t t;
struct tm * timeStruct;
char timeBuf[6];
time(&t);
timeStruct = localtime(&t);
strftime (timeBuf, 6, "%d%b%y", timeStruct)
Regards,
Yusuf
精彩评论