在文件名中显示日期和时间



我试图创建一个以当前日期和时间(用下划线分隔(为文件名的文件,但在编译时遇到以下错误:

main.c:45:31: error: ‘%02d’ directive writing between 2 and 11 bytes into a region of size between 1 and 17 [-Werror=format-overflow=]
45 |   sprintf(fileName,"%04d_%02d_%02d_%02d_%02d_%02d",ptm->tm_year + 1900, ptm->tm_mon+1, ptm->tm_mday, ptm->tm_hour, ptm->tm_min,ptm->tm_sec);
cc1: all warnings being treated as errors

如何抑制此警告/解决此问题?

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <math.h>
#include <string.h>
#include <time.h>
int main(int argc, char *argv[]) {
time_t rawtime;
time(&rawtime);
struct tm * ptm = localtime(&rawtime);
char fileName[25];
sprintf(fileName,"%04d_%02d_%02d_%02d_%02d_%02d",ptm->tm_year + 1900, ptm->tm_mon+1,
ptm->tm_mday, ptm->tm_hour, ptm->tm_min,ptm->tm_sec);
}

要将"%02d"的转换限制为2位,请在int上执行% 100u并使用"%02u"

sprintf(fileName,"%04u_%02u_%02u_%02u_%02u_%02u",
(ptm->tm_year + 1900) % 10000u, (ptm->tm_mon+1)%100u, ptm->tm_mday%100u,
ptm->tm_hour%100u, ptm->tm_min%100u, ptm->tm_sec%100u);

或者为更坏的情况做好准备输出

// 5 _ and 6 INT_MIN and 
char fileName[5 + 6*11 + 1];
sprintf(fileName,"%04du_%02d_%02d_%02d_%02d_%02d",
ptm->tm_year + 1900, ptm->tm_mon+1, ptm->tm_mday
ptm->tm_hour, ptm->tm_min, ptm->tm_sec);

您可以采用的另一种方法是使用snprintf (NULL, 0, format, vals...)来确定如果有足够的可用空间,将写入的字符数(不包括终止的空字节(。因此,您可以使用调整fileName的大小

char fileName[snprintf(NULL, 0, format, vals...) + 1];

在您的情况下,可能是:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <math.h>
#include <string.h>
#include <time.h>
int main (void) {

time_t rawtime;
time(&rawtime);
struct tm *ptm = localtime(&rawtime);

/* use snprintf (NULL, 0, format, vals...) to find max number of chars
* required (excluding the terminating null-byte).
*/
char fileName[snprintf(NULL, 0,"%04d_%02d_%02d_%02d_%02d_%02d",
ptm->tm_year + 1900, ptm->tm_mon+1, ptm->tm_mday, 
ptm->tm_hour, ptm->tm_min,ptm->tm_sec) + 1];

sprintf(fileName,"%04d_%02d_%02d_%02d_%02d_%02d",
ptm->tm_year + 1900, ptm->tm_mon+1, ptm->tm_mday, 
ptm->tm_hour, ptm->tm_min,ptm->tm_sec);
}

还要注意,程序中没有使用argcargv,因此main()的正确调用是int main (void),以明确程序不接受任何参数(并避免任何-Wunused警告…(。

最新更新