The time function in C always displays "Wed Dec 31 23:59:59 1969"

I need the current date and time to be logged for my application. I wrote the code in C. I attached the code

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

int main()
{   time_t t;


     while(1)
     { time(&t);
       printf("Today date and time : %s",ctime(&t));   
     } 

}

Output signal

Today date and time : Wed Dec 31 23:59:59 1969
Today date and time : Wed Dec 31 23:59:59 1969
Today date and time : Wed Dec 31 23:59:59 1969
Today date and time : Wed Dec 31 23:59:59 1969

The time has not been updated since UNIX started. I ran the same program on another computer and everything went fine. Why am I getting this error on my computer and how to solve it?

thanks

Any help was appreciated.

EDIT: An error occurred in the code, I fixed it so that the time is updated in the while loop

+4
source share
2 answers

You have an error returned time, see docs :

((time_t) -1), errno .

, a -1 EPOCH - , . time, , t - -1. , ?

time -1, , , errno, , . , -, , time, EFAULT, :

t .

UPDATE. , , :

time_t t = time(NULL);

, .

, , , -1 t, -1 time(), . , t -1. , , , , , , t -1 . - ? , , &t - , EFAULT, t -1 .

+5

, . , RTC ( ).

, :

, , , . , RTC /AT.

EFAULT , :

t

, .

EFAULT :

#define EFAULT          14      /* Bad address */


, . :

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

int main()
{

    time_t *t;
    t=(time_t*)malloc(sizeof(*t));
    time(t);
    printf("Today date and time : %s",ctime(t));
    free(t); //Clean up the mess we've created
    return 0;
}

.

: RTC

-1

Source: https://habr.com/ru/post/1621764/


All Articles