Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read data into a time_t variable using scanf()?

This code gives me warnings:

$ cat test.c
#include<stdio.h>
#include<time.h>

int main() {

    time_t t;
    scanf("%lld", &t);
    printf("%lld\n", t);
    return 0;
}
$ gcc test.c -o test
test.c: In function ‘main’:
test.c:7: warning: format ‘%lld’ expects type ‘long long int *’, but argument 2 has type ‘time_t *’
test.c:8: warning: format ‘%lld’ expects type ‘long long int’, but argument 2 has type ‘time_t’
$ 

Apart from the warnings, the code works as expected.

What should I do to not get the warnings on compilation (no compiler pragma tricks please)?

like image 648
Lazer Avatar asked Nov 13 '10 07:11

Lazer


3 Answers

The exact type of time_t depends on your platform and OS. It's still quite often 32 bit (either int or long), not 64, and some even use floats. The correct thing to do is to read into a known-size integer (either int or long long) and then assign the value to a time_t as a second step.

like image 93
Fabian Giesen Avatar answered Oct 16 '22 11:10

Fabian Giesen


You need the format to match the time_t definition of your system. Compile with

gcc test.c -o test --save-temps

then

grep time_t test.i|grep typedef

Most likely, this will tell you that time_t is "long int", so you need to scan it with "%ld".

like image 3
Martin v. Löwis Avatar answered Oct 16 '22 11:10

Martin v. Löwis


First, your compiler is right: nothing guarantees that time_t is actually a 64-bit signed integer. It could be a 32-bit integer or even a floating-point value, depending on the platform.

Now, if you're absolutely, positively sure that time_t is a long long on your platform, and you want to avoid the formatting warnings, you can do:

time_t t;
scanf("%lld", (long long *) &t);
printf("%lld\n", (long long) t);
like image 2
Frédéric Hamidi Avatar answered Oct 16 '22 10:10

Frédéric Hamidi