//這是一個利用當前時間作為參數(shù)來創(chuàng)建新文件的應用
//新文件的格式為File+時+分+秒
//應用代碼首先使用time系列函數(shù)獲得當前的時、分、秒信息
//然后通過組合獲得對應的字符串傳遞給Open函數(shù)創(chuàng)建文件
//最后在文件中寫入一個含有時間參數(shù)的字符串
#include
#include
#include
#include
int main(void)
{
time_t timetemp; //定義一個時間結構體變量
struct tm *p; //結構體指針
int i;
char timebuf[7]; //時間信息,注意加上\0
char writetimebuf[7]; //寫文件時間緩沖區(qū)
char filenamebuf[10] = "File"; //文件頭
char writebuf[30]="this is a test! the time is ";
char enterbuf[3]="\r\n"; //回車換行buf
int fd;
int temp;
time(&timetemp); //獲得時間參數(shù)
printf("當前時間為%s",asctime(gmtime(&timetemp))); //不需要添加回車換行符
p = localtime(&timetemp);
printf("%d:%d:%d\n",p->tm_hour,p->tm_min,p->tm_sec);
sprintf(timebuf,"%02d%02d%02d",p->tm_hour,p->tm_min,p->tm_sec);
//將時、分秒信息按照2位前端補0的方式格式化送入時間buf
printf("step1 timebuf is %s\n",timebuf);
strcpy(writetimebuf,timebuf); //復制字符串
printf("writetimebuf is %s\n",writetimebuf);
strcat(filenamebuf,timebuf);
printf("step2 timebuf is %s\n",timebuf);
printf("filenamebuf is %s\n",filenamebuf);
fd = open(filenamebuf,O_RDWR|O_CREAT,S_IRWXU); //創(chuàng)建文件
strcat(writebuf,writetimebuf); //連接兩個字符串
strcat(writebuf,enterbuf); //回車換行
temp = write(fd,writebuf,strlen(writebuf)); //寫入一個字符串以表示正確
temp = close(fd);
return 0;
}
當前題目:[Linux文件]使用當前時間信息作為文件名來創(chuàng)建文件
文章來源:
http://weahome.cn/article/jihhci.html