Dom*_*k C 3 c time cross-platform
我有一个问题.我需要得到像一年中的一天,一个月中的某一天,一年中的一些等等.我使用此代码:
#include <stdio.h>
#include <time.h>
int main(void)
{
time_t liczba_sekund;
struct tm strukt;
time(&liczba_sekund);
localtime_r(&liczba_sekund, &strukt);
printf("today is %d day of year\nmonth is %d, month's day %d\n", strukt.tm_yday+1, strukt.tm_mon+1, strukt.tm_mday);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
第一件事:为什么gcc -std = c99 -pedantic -Wall会返回此警告:
我的输入:gcc test_data.c -o test_data.out -std = c99 -pedantic -Wall
输出:
test_data.c:在函数'main'中:
test_data.c:11:3:警告:函数'localtime_r'的隐式声明[-Wimplicit-function-declaration]
第二件事:如何让它在Windows上运行?在尝试使用Dev-C编译它时,我得到了这个:http: //imgur.com/U7dyE
@@ EDIT --------------------我找到了一个当地时间建议的例子:
#include <stdio.h>
#include <time.h>
int main ()
{
time_t time_raw_format;
struct tm * ptr_time;
time ( &time_raw_format );
ptr_time = localtime ( &time_raw_format );
printf ("Current local time and date: %s", asctime(ptr_time));
return 0;
}
Run Code Online (Sandbox Code Playgroud)
如何将此更改为日期格式:5.12.2012或5-12-2012?如何获得一年中的一天?
如果解决方案在Windows和Linux上都有效,我会很高兴.
localtime_r
不属于C标准.也许你在找localtime
?
localtime_r
在许多Linux系统上真的可用:
线程安全版本asctime_r(),ctime_r(),gmtime_r()和localtime_r()由SUSv2指定,并且自libc 5.2.5起可用
但是,由于它不是标准的一部分,因此无法在Windows上使用它.
如何将此更改为日期格式:5.12.2012或5-12-2012?如何获得一年中的一天?
你必须使用strftime
而不是asctime
:
int main ()
{
time_t time_raw_format;
struct tm * ptr_time;
char buffer[50];
time ( &time_raw_format );
ptr_time = localtime ( &time_raw_format );
if(strftime(buffer,50,"%d.%m.%Y",ptr_time) == 0){
perror("Couldn't prepare formatted string");
} else {
printf ("Current local time and date: %s", buffer);
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)