-1

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); }
    }
  • Can you be more specific as to the nature of the problem? – Scott Hunter Mar 19 '20 at 16:17
  • 1
    Be aware that fwrite'ing a struct is risky. You will want a more robust serialization mechanism, since the struct size may change on different platforms. Since you're writing and reading on the same host, this is not likely to be an issue at the moment, but it's something to be aware of. – William Pursell Mar 19 '20 at 16:22

1 Answers1

0

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));
}  
William Pursell
  • 204,365
  • 48
  • 270
  • 300