c语言获取时间并存储,如何在C程序中获取日期和时间值?
strftime (C89)
馬丁提到過,這是一個例子:
main.c
#include
#include
#include
int main(void) {
time_t t = time(NULL);
struct tm *tm = localtime(&t);
char s[64];
assert(strftime(s, sizeof(s), "%c", tm));
printf("%s\n", s);
return 0;
}
GitHub上游。
編譯并運行:
gcc -std=c89 -Wall -Wextra -pedantic -o main.out main.c
./main.out
樣本輸出:
Thu Apr 14 22:39:03 2016
的%c說明符產生相同的格式ctime。
此函數的一個優點是它返回寫入的字節數,以防在生成的字符串過長的情況下更好地控制錯誤:
返回值
Provided? that? the? result string, including the terminating null byte, does not exceed max bytes, strftime() returns the number of bytes (excluding the terminating null byte) placed in the array s.? If the length of the result string (including the terminating null byte) would exceed max bytes, then
strftime() returns 0, and the contents of the array are undefined.
Note that the return value 0 does not necessarily indicate an error.? For example, in many locales %p yields an empty string.? An empty format string will likewise yield an empty string.
asctime和ctime(C89)
asctime是格式化a的便捷方法struct tm:
main.c
#include
#include
int main(void) {
time_t t = time(NULL);
struct tm *tm = localtime(&t);
printf("%s", asctime(tm));
return 0;
}
樣本輸出:
Wed Jun 10 16:10:32 2015
而且也有ctime()其標準說是一條捷徑:
asctime(localtime())
正如喬納森·萊夫勒(Jonathan Leffler)所提到的,該格式的缺點是沒有時區信息。
POSIX 7將這些功能標記為“過時”,因此可以在以后的版本中將其刪除:
標準開發人員決定將asctime()和asctime_r()函數標記為過時,即使asctime()在ISO C標準中,這也可能會導致緩沖區溢出。ISO C標準還提供了strftime()函數,可用于避免這些問題。
這個問題的C ++版本:如何在C ++中獲取當前時間和日期?
在Ubuntu 16.04中測試。
總結
以上是生活随笔為你收集整理的c语言获取时间并存储,如何在C程序中获取日期和时间值?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: c语言对分查找实验报告,C语言实验指导.
- 下一篇: OJ题目细菌实验分组c语言,C语言