【问题标题】:Reading and displaying time stamp from a binary file从二进制文件中读取和显示时间戳
【发布时间】:2020-06-30 19:35:32
【问题描述】:

我目前正在从事一个大学 c 项目,其中我将保存在结构中的读数写入二进制文件。在这个结构中,我还保存了输入项目的时间和日期。然后我在一个单独的程序中打开文件并读取工作正常的值但是我很难弄清楚如何读取文件中保存的时间和日期并将其显示到屏幕上。下面是我的第二个程序中该部分的代码。

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#pragma warning(disable : 4996)

struct readings {
    double temperature;
    double wind_direction;
    double wind_speed;
    time_t time;
};



int main(void)
{
    struct readings* readings = NULL;
    int option;
    printf_s("Welcome to Data Acquisition Program\n");
    printf_s("Options are as follows:\n 1:Load File\n 2:Search Weather by date\n 3:View Monthly Data\n 4:Export to Excel\n 5:Exit\n");
    printf_s("Enter an option: ");
    scanf_s("%d", &option);

    if (option == 1)
    {

        FILE* pFile;
        errno_t error;
        int num_readings;
        //struct readings* time_t time;
        time_t t;
        struct tm* tmp;
        char MY_TIME[50];
        time(&t);

        tmp = localtime(&t);

        error = fopen_s(&pFile, "weather.bin", "rb");

        if (error == 0)
        {
            fread(&num_readings, sizeof(int), 1, pFile);
            readings = malloc(sizeof(struct readings) * num_readings);
            fread(readings, sizeof(struct readings), num_readings, pFile);

            strftime(MY_TIME, sizeof(MY_TIME), "%x - %I:%M%p", tmp);
            printf("Date & Time: %s\n", MY_TIME);

            for (int i = 0; i < num_readings; i++)
            {
                printf_s("Temperature: %lf\n", readings[i].temperature);
                printf_s("Wind Direction: %lf\n", readings[i].wind_direction);
                printf_s("Wind Speed: %lf\n", readings[i].wind_speed);
            }
            fclose(pFile);
        }
        else { printf_s("Error: %d", error); }
    }

【问题讨论】:

  • 您能否更具体地说明问题的性质?
  • 请注意,fwrite 结构是有风险的。您将需要更健壮的序列化机制,因为结构大小可能会在不同平台上发生变化。由于您在同一主机上进行写作和阅读,目前这不太可能成为问题,但需要注意。

标签: c struct time-t


【解决方案1】:

我想你正在寻找

ctime(&(readings[i].time))

但请不要使用这种表示法。相反,做

for (struct readings *t = readings; t < readings + num_readings; t++) {
        printf_s("Temperature: %lf\n", t->temperature);
        printf_s("Wind Direction: %lf\n", t->wind_direction);
        printf_s("Wind Speed: %lf\n", t->wind_speed);
        printf_s("Time: %s\n", ctime(&t->time));
}  

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-24
    • 2015-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-19
    • 1970-01-01
    相关资源
    最近更新 更多