#include<stdio.h>
#include<time.h>
int main(){
char filepath[100];
char datevar[15];
char command[30];
struct tm *t1;
time_t now ;
time(&now);
memcpy(&t1,localtime(&now),sizeof(t1));
t1 = localtime(&now);
memset(filepath,0,sizeof(filepath));
sprintf(datevar,"%04d%02d%02d",t1->tm_year+1900,t1->tm_mon+1,t1->tm_mday);
strcpy(filepath,"abc");
strcat(filepath,"/xyx/");
strcat(filepath,datevar);
strcat(filepath,"/");
printf("filepath 1:- %s\n",filepath);
sprintf(command, "hello %s good path",filepath);
printf("filepath 2:- %s\n",filepath);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
在上面的程序中,两者printf都是不同的打印filepath.我得到的输出: -
filepath 1:- abc/xyx/20130430/
filepath 2:- h
Run Code Online (Sandbox Code Playgroud)
我的问题是,如果我使用它,为什么会改变文件路径sprintf.
这是因为
char command[30];
Run Code Online (Sandbox Code Playgroud)
不足以容纳
sprintf(command, "hello %s good path",filepath);
Run Code Online (Sandbox Code Playgroud)
看起来最终'h'和0终止符进入filepath. (Which is coincidental, sincesprintf ing more into命令,而不是它可以调用未定义的行为.)