c - 如何使用C代码从文本文件中读取时间戳数据?

标签 c linux

我正在使用c代码连续将数据写入带有时间戳的文本文件中,如何从文本文件中读取一天/两天/一周/一年的数据?以下是示例文本文件数据。

20190629105716 value1:15 value2:25 value3:622
20190629105716 value1:15 value2:25 value3:622
20190630105716 value1:15 value2:25 value3:622
20190701105716 value1:15 value2:25 value3:622
20190702105716 value1:15 value2:25 value3:622
20190703105716 value1:15 value2:25 value3:622
20190704105716 value1:15 value2:25 value3:622
20190705105716 value1:15 value2:25 value3:622

最佳答案

除了日期不一致的问题之外,Jonathan 的评论还包含了解决方案。然而,正确使用这些功能并非易事。以下是如何使用 strptime 的简短示例和 sscanf在这种情况下。

我对以下代码进行了简化,要求输入数据中的每一行都具有固定的最大长度。这个假设可能是安全的,但如果违反的话,代码就会严重崩溃。不幸的是,处理可变的行长度会使此类代码变得更加复杂。

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

#define MAX_LINE 1024

int main(void) {
    char line[MAX_LINE];

    while (fgets(line, MAX_LINE, stdin) != NULL) {
        struct tm tm;
        char *temp_ptr = strptime(line, "%a %b %d %H:%M:%S %Y", &tm);
        if (temp_ptr == NULL) {
            fprintf(stderr, "Error parsing date at \"%s\"\n", line);
            return EXIT_FAILURE;
        }

        int temp;
        if (sscanf(temp_ptr, " temp : %d", &temp) == 0) {
            fprintf(stderr, "Error parsing temperature at \"%s\"\n", temp_ptr);
            return EXIT_FAILURE;
        }

        // At this point we’ve successfully parsed the date and temperature.
        // Now we can use it. As a simple example, we just print it again:

        char time_str[20];
        strftime(time_str, sizeof time_str, "%Y-%m-%d %H:%M:%S", &tm);
        printf("Temperature %d on %s\n", temp, time_str);
    }

    if (! feof(stdin)) {
        fprintf(stderr, "Error reading input\n");
        return EXIT_FAILURE;
    }

    return EXIT_SUCCESS;
}

此代码从 stdin 读取数据。酌情更改。

此外,此代码使用当前区域设置来解析工作日和月份名称。一般来说,您会希望对此施加更多控制。更好的是,通过更改数据格式,完全不要依赖日期的“自然语言名称”。将日期存储为“Wed Jul 4 ...”仅对人类读者有意义,对于机器阅读来说根本没有意义。存储机器可读日期的唯一可接受的方式是 ISO 8601 (又名 YYYY-MM-DD)或 POSIX time .

关于c - 如何使用C代码从文本文件中读取时间戳数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56880765/

相关文章:

php - linux shell 脚本 : how can I create a service that will run in background?

c - 用 C 语言存储 .dat 文件中的整数和 float

python - 在 C 中嵌入 Python 以获取配置文件

c - PostgreSQL - ECPG/C - 主机变量 UTF-8 解码

c - 未找到 read() 结束行导致代码输出奇怪的符号

linux - 服务文件未在 Ubuntu 上运行,但项目/文件在 Putty/终端上运行良好(ASP.NET Core 网站)

linux - sh 中的子字符串返回 "Bad substitution"

c - 如何用 NCurses 清除特定行?

linux - 如何从脚本中为 sudo 提供密码?

linux - 在 udev 中替换 hal-get-property 和 hal-find-by-capability?