【问题标题】:How to read a date from file in c如何在c中从文件中读取日期
【发布时间】:2019-08-06 01:50:35
【问题描述】:

我正在使用 C 从程序中的文件中读取。在文件中,我有一些日期,每个日期都在单独的行中,就像这样:

20190101
20190304
20180922

现在我希望程序将这些作为日期读取,并找出当前日期与这些日期之间的差异。是否可以将这些日期转换为 C 可读的格式?像这样的东西:2019.01.01 目前,我使用fgets 阅读它,但无法将其转换为上述格式。 这是我的代码:

#include <stdio.h>
#include <stdlib.h>
void FileRead(FILE *pr)
{
    char date [15];
    fgets(date,15,pr);
    printf("date : %s", date);

}
int main()
{
   char x;
   FILE *pr;
   pr=fopen("mytextfile.txt","r");
   if(pr==NULL)
   {
       printf("File can not be opened.");
       return 0;
   }
  while(scanf("%c", &x))
    {
        switch(x)
        {

        case 'v' :
            FileRead(pr);
        break;

        case 'k' :
            return 0;

        }
    }
fclose(pr);
    return 0;
}

【问题讨论】:

  • C 有一个内置的日期处理库:en.wikipedia.org/wiki/C_date_and_time_functions
  • 有没有什么办法可以把这个日期作为输入,找出当前和输入的区别?
  • @TomasAnda 是的,但是如果您没有在您的问题中尝试自己执行此操作(请参阅如何创建 minimal reproducible example),不会有多少人愿意帮助您。
  • " 目前,我使用 fgets 读取它,但无法将其转换为上述格式" --> 发布您的代码,否则这只是为我编写代码发布。跨度>
  • 是的,您阅读每一行,将year, mo, day 分开并使用它来填充struct tm(然后将代表分解时间),然后将其传递给mktime 以转换为time_t 可以用来获取与当前时间的秒差(通常使用localtime() 获取)。

标签: c file date fgets


【解决方案1】:

从现在到现在处理差异的最简单方法是从文件中读取日期并将它们解析为月、日和年 (m, d, y)。如果您不打算对每次转换进行完整验证,那么分隔 4 位数年份和 2 位数月份和日期的简单方法是使用 fscanf 和适当的 field-width 将转换限制为所需位数的修饰符,例如

    while (fscanf (fp, "%4d%2d%2d", &y, &m, &d) == 3) {

然后在循环中所需要的就是用年、月和日值填充struct tm(记得从年中减去1900,并将小时、分钟和秒中的每个成员设置为零和夏令时成员-1)。一个简单的函数可以做到这一点,并在调用mktime后返回time_t,例如

time_t fill_broken_down_time (int y, int m, int d)
{                   /* initialize struct members */
    struct tm bdt = { .tm_sec=0, .tm_min=0, .tm_hour=0, .tm_mday=d, 
                    .tm_mon=m>0?m-1:0, .tm_year=y-1900, .tm_isdst=-1 };

    return mktime(&bdt);    /* return mktime conversion to time_t */
}

最后,您只需要获取time_t 值并调用difftime 以获取当前时间与从文件中读取的时间之间的秒差作为double 值。在main() 中继续循环,例如

    while (fscanf (fp, "%4d%2d%2d", &y, &m, &d) == 3) {
        time_t  now = time(NULL),
                then = fill_broken_down_time (y, m, d);
        printf ("date[%d] %d/%d/%d is %.2f seconds from now.\n", 
                n++, m, d, y, difftime (now, then));
    }

总而言之,您可以执行以下操作:

#include <stdio.h>
#include <time.h>

time_t fill_broken_down_time (int y, int m, int d)
{                   /* initialize struct members */
    struct tm bdt = { .tm_sec=0, .tm_min=0, .tm_hour=0, .tm_mday=d, 
                    .tm_mon=m>0?m-1:0, .tm_year=y-1900, .tm_isdst=-1 };

    return mktime(&bdt);    /* return mktime conversion to time_t */
}

int main (int argc, char **argv) {
    /* use filename provided as 1st argument (stdin by default) */
    FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;
    int y, m, d, n = 1;

    if (!fp) {  /* validate file open for reading */
        perror ("file open failed");
        return 1;
    }

    while (fscanf (fp, "%4d%2d%2d", &y, &m, &d) == 3) {
        time_t  now = time(NULL),
                then = fill_broken_down_time (y, m, d);
        printf ("date[%d] %d/%d/%d is %.2f seconds from now.\n", 
                n++, m, d, y, difftime (now, then));
    }
    if (fp != stdin) fclose (fp);   /* close file if not stdin */

    return 0;
}

注意:程序期望文件名从作为程序的第一个参数读取日期(或者如果没有给出参数,程序默认从stdin读取))

输入文件示例

$ cat dat/3dates.txt
20190101
20190304
20180922

使用/输出示例

$ ./bin/time_from_now dat/3dates.txt
date[1] 1/1/2019 is 6300212.00 seconds from now.
date[2] 3/4/2019 is 943412.00 seconds from now.
date[3] 9/22/2018 is 15030212.00 seconds from now.

编辑每条评论修改输入文件格式

如果您的数据文件实际上与您最初随问题发布的三行日期不同,并且它包含日期信息之前的标题行,那么您需要在处理日期行之前阅读、识别和处理这些行.由于您希望以天而不是秒为单位输出,您只需将秒数除以86400 即可获得以天为单位的时间差。

要读取句柄标题行,只需将您的读取调整为一次将整行读取到足够大小的缓冲区中。声明一个足够大的常数以确保您的缓冲区足够大,例如

#define MAXC 1024u  /* if you need a constant, #define one (or more) */
...
int main (int argc, char **argv) {
...
    char buf[MAXC];     /* buffer to hold each line read from file */

然后您将简单地使用sscanf 而不是fscanf 对每一行的信息进行完全相同的解析。如果行格式不满足 yyyymmdd 格式,您知道它不是日期行 - 以任何您想要的方式处理这些行(它们只是在下面的示例中以前缀 "non-date line: " 输出。

将自文件中的时间以来的秒数除以每天86400 秒,您的新读取循环将类似于:

    while (fgets (buf, MAXC, fp)) {     /* read each line in file */
        /* if line isn't a date line, just output line as non-date line */
        if (sscanf (buf, "%4d%2d%2d", &y, &m, &d) != 3) {
            printf ("non-date line: %s", buf);
            continue;
        }
        time_t  now = time(NULL),
                then = fill_broken_down_time (y, m, d);
        double secs = difftime (now, then); /* get seconds between dates */
        printf ("date[%d] %02d/%02d/%04d is %11.2f sec (%g days) from now.\n", 
                n++, m, d, y, secs, secs / 86400.0);
    }

你说:

"I am not able to open the file"

程序希望您提供要读取的文件名作为程序的第一个参数,否则程序默认从stdin 读取。这意味着您必须向程序提供文件名,例如

./yourprogram your_date_file

或者您必须在stdin 上提供该数据,方法是将该信息从某个其他程序的输出传送到该程序,或者简单地将文件重定向为stdin 上的输入,例如

some_utility_making_dates | ./yourprogram

./yourprogram < your_date_file

结合所有更改,您的程序将如下所示:

#include <stdio.h>
#include <time.h>

#define MAXC 1024u  /* if you need a constant, #define one (or more) */

time_t fill_broken_down_time (int y, int m, int d)
{                   /* initialize struct members */
    struct tm bdt = { .tm_sec=0, .tm_min=0, .tm_hour=0, .tm_mday=d, 
                    .tm_mon=m>0?m-1:0, .tm_year=y-1900, .tm_isdst=-1 };

    return mktime(&bdt);    /* return mktime conversion to time_t */
}

int main (int argc, char **argv) {
    /* use filename provided as 1st argument (stdin by default) */
    FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;
    int y, m, d, n = 1;
    char buf[MAXC];     /* buffer to hold each line read from file */

    if (!fp) {  /* validate file open for reading */
        perror ("file open failed");
        return 1;
    }

    while (fgets (buf, MAXC, fp)) {     /* read each line in file */
        /* if line isn't a date line, just output line as non-date line */
        if (sscanf (buf, "%4d%2d%2d", &y, &m, &d) != 3) {
            printf ("non-date line: %s", buf);
            continue;
        }
        time_t  now = time(NULL),
                then = fill_broken_down_time (y, m, d);
        double secs = difftime (now, then); /* get seconds between dates */
        printf ("date[%d] %02d/%02d/%04d is %11.2f sec (%g days) from now.\n", 
                n++, m, d, y, secs, secs / 86400.0);
    }
    if (fp != stdin) fclose (fp);   /* close file if not stdin */

    return 0;
}

带标题的示例输入文件

$ cat dat/3dates-w-headers.txt
This file contains dates to read and convert to days.
The file also contains this description and dates in the format:

yyyymmdd
20190101
20190304
20180922

使用/输出示例

$ ./bin/time_from_now2 dat/3dates-w-headers.txt
non-date line: This file contains dates to read and convert to days.
non-date line: The file also contains this description and dates in the format:
non-date line:
non-date line: yyyymmdd
date[1] 01/01/2019 is  6348645.00 sec (73.4797 days) from now.
date[2] 03/04/2019 is   991845.00 sec (11.4797 days) from now.
date[3] 09/22/2018 is 15078645.00 sec (174.521 days) from now.

检查一下,如果您还有其他问题,请告诉我。

【讨论】:

  • 我无法打开文件。另外,我想展示天数的差异。如果第一行是一个名字第二个姓氏和第三个日期怎么办?
  • 竖起大拇指,大卫!这看起来是一个了不起的解决方案,应该是答案。我想到了别的东西,我们可以在使用fgetsscanf 从文件中读取的同时使用 if 语句吗?如果是,那么我想为这个问题添加一些其他内容。
  • 当然,这就是编程的美妙之处,您可以在任何循环中添加您喜欢的任何附加条件。我刚刚检查该行是否无法解析为y, m d 的条件——如果是,我按照上面的说明打印它并获取下一行。你可以随心所欲地改变它。试一试,如果您有问题,请告诉我。
  • 现在工作正常。我欠你很多。谢谢。
  • 您想要做的是使用计数器n 来控制您正在阅读的内容。你可以简单地做while (fgets(..)) { switch (n) { case 1: /*handle 1st line*/ break; case 2: /*handle plate number*/ break, ....另一个选项是测试每一行的内容——但如果你知道它有一个固定的格式和行包含的内容,那么一个简单的计数器和switchif (n == 1)... else if (n == 2)... else if ...是更简单的方法。
【解决方案2】:

通过fgets 获得char* 后,使用atoi 转换为整数。然后你有 YYYYMMDD 格式的日期。然后就可以了

const int day = dateYYYYMMDD % 100;
const int month = (dateYYYYMMDD % 10000)/100;
const int year = dateYYYYMMDD / 10000;

您可以使用C Date and time functions 获取当前日期。

要使当前日期与这些日期不同,一种选择是将所有日期转换为Julian date,然后对朱利安日期进行数字差异。

如果获取儒略日期很困难,请标准化为同一年(根据年份添加 365 或 366 是闰或不是闰,因为您从较低的年份到较高的年份)。然后到同月再做日差。

【讨论】:

  • 避免使用atoi 提供了 验证转换的能力。而是使用strtol。或者虽然不是很好,但最好用fgets 阅读,用sscanf 解析。至少,您可以衡量转换的成功/失败。
【解决方案3】:

输出是,你只需循环文件行并在其中设置一个 if 条件

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>

int main(void)
{
    char buff[20];
    time_t now = time(NULL);

    strftime(buff, 20, "%Y%m%d\n", localtime(&now));
    printf("Today : %s \n\n", buff);

    static const char filename[] = "file.txt";
    FILE *file = fopen(filename, "r");

    if (file != NULL)
    {
        char line[128]; /* or other suitable maximum line size */
        while (fgets(line, sizeof line, file) != NULL) /* read a line */
        {
            fputs(line, stdout); /* write the line */

            if (strcmp(line, buff) == 0)
                printf("\nThis line of date equal to current date\n");

        }
        fclose(file);
    }
    else
    {
        perror(filename); /* why didn't the file open? */
    }
    return 0;
}

文件.txt

20190315
20190304
20180922

【讨论】:

  • 未定义对 getline 的引用。
  • 答案是正确的,我只是在我的 Ubuntu 系统中运行它,你的平台是哪个?窗户? linux?苹果 ?是系统配置错误!在 [link] (stackoverflow.com/questions/13112784/…) 的帮助下使用您的源代码更改 #define _GNU_SOURCE
  • 它打印当前日期,但问题仍然存在,现在想象第一行有一个单词,第二行有一个单词,第三行有日期。现在如何只读取第三行(日期)并从当前日期减去天数?
  • 问题仍然存在是什么意思?未定义对 getline 的引用。??
  • 不,现在很好。如果第一行有一个单词,第二行有一个单词,第三行有日期怎么办。现在如何只读取第三行(日期)并从当前日期减去天数?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-27
  • 1970-01-01
  • 2021-09-13
  • 2023-03-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多