如何使用fscanf从顺序访问文件中读取时间戳?

时间:2014-03-19 23:36:45

标签: c windows file timestamp

下面的代码显示并将当前时间存储到文本文件中,我将如何从文件中读取它?


void main()
{   
    char p[4];
    char t[4];
    int one;
    int two;

    FILE * fp;
    time_t ltime; /* calendar time */
    ltime=time(NULL); /* get current cal time */
    printf("%s",asctime( localtime(&ltime) ) );
    getch();

    fp=fopen("testtime.txt","w+");
    fprintf(fp,asctime( localtime(&ltime) ) );
    getch();
    fclose(fp);
}

1 个答案:

答案 0 :(得分:0)

asctime()来自C规范。

char *asctime(const struct tm *timeptr) {
  static const char wday_name[7][3] = { "Sun", "Mon", "Tue", "Wed", "Thu",
          "Fri", "Sat" };
  static const char mon_name[12][3] = { "Jan", "Feb", "Mar", "Apr", "May",
          "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  static char result[26];
  sprintf(result, "%.3s %.3s%3d %.2d:%.2d:%.2d %d\n",
          wday_name[timeptr->tm_wday], mon_name[timeptr->tm_mon],
          timeptr->tm_mday, timeptr->tm_hour, timeptr->tm_min, timeptr->tm_sec,
          1900 + timeptr->tm_year);
  return result;
}

简单地反转它。

#include<time.h>

// 0:Success, 1:failure
int un_asctime(struct tm *timeptr, FILE *fp) {
  static const char wday_name[7][4] = { "Sun", "Mon", "Tue", "Wed", "Thu",
          "Fri", "Sat" };
  static const char mon_name[12][4] = { "Jan", "Feb", "Mar", "Apr", "May",
          "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  char wday[4];
  char mon[4];
  int n;
  char buffer[100];

  if (fgets(buffer, sizeof buffer, fp) == NULL) return 0;
  int cnt = sscanf(buffer, "%3s%3s%d%d:%d:%d%d%n", wday, mon,
          &timeptr->tm_mday, &timeptr->tm_hour,
          &timeptr->tm_min, &timeptr->tm_sec,
          &timeptr->tm_year, &n);
  if (cnt != 7 || src[n] != '\n' || src[n + 1] != '\0'
    ) return 1;
  timeptr->tm_year -= 1900;
  timeptr->tm_isdst = -1;  // unknown DST setting
  for (timeptr->tm_wday = 0; timeptr->tm_wday < 7; timeptr->tm_wday++) {
    if (strcmp(wday, wday_name[timeptr->tm_wday]) == 0)
      break;
  }
  for (timeptr->tm_mon = 0; timeptr->tm_mon < 12; timeptr->tm_mon++) {
    if (strcmp(mon, mon_name[timeptr->tm_mon]) == 0)
      break;
  }
  if (timeptr->tm_wday == 7 || timeptr->tm_mon == 12)
    return 1;
  timeptr->tm_yday = 0; // TBD
  return 0;
}