//這是一個(gè)在參數(shù)指定文件中連續(xù)寫(xiě)入當(dāng)前時(shí)間的應(yīng)用 //每隔1分鐘在當(dāng)前目錄下建立一個(gè)新文件,通過(guò)tm_sec是否為0來(lái)判斷 //文件以1秒為時(shí)間間隔,將當(dāng)前的時(shí)間寫(xiě)入文件,然后回車(chē)換行 #include#include #include #include #include int main(int argc,char *argv[]) { time_t filetime;//時(shí)間結(jié)構(gòu)體對(duì)象 struct tm *p;//時(shí)間結(jié)構(gòu)體指針 int temp,seektemp; //偏移量計(jì)算中間量 int fd; //文件描述符 char writebuf[50]; //寫(xiě)字符串緩沖區(qū) char filenamebuf[10] = "File"; //文件名稱(chēng)緩沖區(qū) char timebuf[6]; //時(shí)間緩沖區(qū) struct timeval timenow,timeold; //時(shí)間變量 struct timezone timez; int j = 0; int writeCounter = 0; //寫(xiě)入計(jì)數(shù)器 if(argc!= 1) //如果參數(shù)錯(cuò)誤 { printf("Plz input the corrcet file name as './exam39lseekFun filename string'!\n"); return 1; //如果參數(shù)不正確則退出 } gettimeofday(&timeold,&timez); //取得一個(gè)時(shí)間信息作為參考時(shí)間信息 time(&filetime);//獲得時(shí)間參數(shù) p = localtime(&filetime);//獲得時(shí)分秒?yún)?shù),以供創(chuàng)建新文件 sprintf(timebuf,"%02d%02d%02d",p->tm_hour,p->tm_min,p->tm_sec); strcat(filenamebuf,timebuf);//創(chuàng)建文件名 strcat(filenamebuf,".txt"); fd=open(filenamebuf,O_RDWR|O_CREAT,S_IRWXU);//創(chuàng)建文件 // fd = open(*(argv+1),O_RDWR|O_CREAT,S_IRWXU); //打開(kāi)文件如果沒(méi)有則創(chuàng)建 while(1) //進(jìn)入主循環(huán) { while(1) //1毫秒延時(shí)判斷 { gettimeofday(&timenow,&timez); //獲取當(dāng)前時(shí)間參數(shù) time(&filetime);//獲得時(shí)間參數(shù) p = localtime(&filetime);//獲得時(shí)分秒?yún)?shù),以供創(chuàng)建新文件 sprintf(timebuf,"%02d%02d%02d",p->tm_hour,p->tm_min,p->tm_sec); //printf("%d:%d:%d\n",p->tm_hour,p->tm_min,p->tm_sec); //時(shí)分秒信息放入timebuf緩沖區(qū)備用 //gettimeofday(&timenow,&timez); //獲取當(dāng)前時(shí)間參數(shù) if((timenow.tv_sec - timeold.tv_sec) == 1) //如果到達(dá)一秒 { timeold = timenow; //更新保存的時(shí)間信息 printf("%d:%d:%d\n",p->tm_hour,p->tm_min,p->tm_sec); //printf("p->tm_sec:%02d\n",p->tm_sec); break; //1秒時(shí)間到,退出 } } if(p->tm_sec==0)//如果是0秒,到1分鐘了 { char filenamebuf[]= "File"; strcat(filenamebuf,timebuf);//創(chuàng)建文件名 strcat(filenamebuf,".txt"); fd=open(filenamebuf,O_RDWR|O_CREAT,S_IRWXU);//創(chuàng)建文件 writeCounter=0; printf("new filename %s\n",filenamebuf); } time(&filetime); //獲得當(dāng)前時(shí)間參數(shù) sprintf(writebuf,"%s",ctime(&filetime)); //將當(dāng)前時(shí)間參數(shù)放入寫(xiě)緩沖區(qū) printf("%s",&writebuf); //在屏幕上打印單簽writebuf的內(nèi)容 if(writeCounter == 0) //第一次寫(xiě)入 { temp = write(fd,writebuf,strlen(writebuf)); //寫(xiě)入數(shù)據(jù) seektemp = lseek(fd,0,SEEK_CUR); //獲得當(dāng)前的偏移量 writeCounter++; //寫(xiě)入計(jì)數(shù)器++ } else { j = strlen(writebuf) * writeCounter; //獲得偏移量 seektemp = lseek(fd,j,SEEK_SET); temp = write(fd,writebuf,strlen(writebuf)); writeCounter++; } } close(fd); return 0; }
已上機(jī)測(cè)試
成都創(chuàng)新互聯(lián)于2013年創(chuàng)立,是專(zhuān)業(yè)互聯(lián)網(wǎng)技術(shù)服務(wù)公司,擁有項(xiàng)目網(wǎng)站建設(shè)、成都網(wǎng)站設(shè)計(jì)網(wǎng)站策劃,項(xiàng)目實(shí)施與項(xiàng)目整合能力。我們以讓每一個(gè)夢(mèng)想脫穎而出為使命,1280元舟曲做網(wǎng)站,已為上家服務(wù),為舟曲各地企業(yè)和個(gè)人服務(wù),聯(lián)系電話(huà):18982081108