Search code examples
cstructtime-t

Reading and displaying time stamp from a binary file


I am currently working on a college c project in which I have wrote readings saved in a struct to a binary file. In this struct I am also saving the time and date of which the items were entered. i am then opening the file in a seperate program and reading in the values which works fine however I am having difficulty sussing out how to read and display the time and date saved in the file to the screen. Below is the code for that section in my second programme.

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

Solution

  • I think you're looking for

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

    But please don't use that notation. Instead, do

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