1

我正在用 C 编写一个网络游戏。我已经在一个文件中写了分数。我还想添加当天的日期。这是文件的结构:日期名称分数和代码:

ScoreFile = fopen("scores.txt", "a");
fprintf(ScoreFile, "%s %d\n", Name, Score);

我试过 system("date") 但它打印在标准输出上。我认为我不能用 fprintf 添加日期。

您知道允许在文件中添加日期的解决方案吗?(也许从 time.h 开始?)

多谢 !!

4

4 回答 4

2

考虑使用strftime将时间结构转换为字符串。

示例(来自上面的链接):

#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);

放入Jul 9, 2011; 17:55:55\n_s

于 2011-07-08T21:24:05.843 回答
1

查看 time.h 中的strptimestrftimemktime

解析:

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
}

来写:

  time_t t;
  struct tm * timeStruct;
  char timeBuf[6];

  time(&t);
  timeStruct = localtime(&t);

  strftime (timeBuf, 6, "%d%b%y", timeStruct)

问候,
优素福

于 2011-07-08T21:29:57.453 回答
1

像这样的东西应该工作

time_t now;
time(&now);

printf("... %s\n", ctime(&now));

如果您需要指定自己的格式,请查看strftime. 如果您以后需要读回并解析它,最好写下自纪元以来的秒数(time_t可能是 ASCII 码?)。

于 2011-07-08T21:22:54.810 回答
1

最简单的方法是:

time_t now = time(NULL);
fprintf(ScoreFile, "[%s] %s %d\n", ctime(&now), Name, Score);
于 2011-07-08T21:25:33.683 回答