time()用来获取系统时间(秒数)
time_t time(time_t *seconds) 1970.1.1 0:0:0
localtime()将系统时间转换成本地时间
struct tm *localtime(const time_t *timer)
struct tm {
int tm_sec; /* 秒,范围从 0 到 59 */
int tm_min; /* 分,范围从 0 到 59 */
int tm_hour; /* 小时,范围从 0 到 23 */
int tm_mday; /* 一月中的第几天,范围从 1 到 31 */
int tm_mon; /* 月份,范围从 0 到 11 */
int tm_year; /* 自 1900 起的年数 */
int tm_wday; /* 一周中的第几天,范围从 0 到 6 */
int tm_yday; /* 一年中的第几天,范围从 0 到 365 */
int tm_isdst; /* 夏令时 */
};
注意:
int tm_mon; 获取的值要加1是正确的月份
int tm_year; 获取的值加1900是正确的年份
#include <time.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
int main(int argc,char *argv[]){
FILE *fp;
time_t ctime;
struct tm *ctimestr;
int linecount = 0;
char buf[32];
fp=fopen("test.txt","a+");
if(fp==NULL){
perror("fopen");
return 0;
}
//calculate test.txt line
while(fgets(buf,32,fp)!=NULL){
if(buf[strlen(buf)-1] =='\n'){//判断buff最后一个是否是换行符,是则行号+1
linecount++;
}
}
while(1){
ctime = time(NULL);
//printf("ctime=%d\n",(int)ctime);
ctimestr = localtime(&ctime);
printf("%04d-%02d-%02d %02d:%02d:%02d\n",ctimestr->tm_year+1900,
ctimestr->tm_mon+1,
ctimestr->tm_mday,
ctimestr->tm_hour,
ctimestr->tm_min,
ctimestr->tm_sec);
fprintf(fp,"%d, %04d-%02d-%02d %02d:%02d:%02d\n",linecount,
ctimestr->tm_year+1900,
ctimestr->tm_mon+1,
ctimestr->tm_mday,
ctimestr->tm_hour,
ctimestr->tm_min,
ctimestr->tm_sec);
fflush(fp);//刷新缓冲区
linecount++;//添加行号
sleep(1);
}
fclose(fp);
}
获取文件内的所有行数量:
while(fgets(buf,32,fp)!=NULL){
if(buf[strlen(buf)-1] =='\n'){ //注意判断是否是一行结束
linecount++;
}
}
作业
每隔1秒向文件1.txt写入当前系统时间,行号递增
#include<stdio.h>
#include<time.h>
#include<unistd.h>
#include<string.h>
int main(){
FILE *fp;
time_t ctime;
struct tm *ctimestr;
int linecount = 0;
char buf[30];
fp = fopen("1.txt","a+");
if(fp == NULL){
perror("fopen");
return 0;
}
while(fgets(buf,32,fp)!=NULL){
if(buf[strlen(buf)-1 == '\n']){
linecount++;
}
}
while(1){
ctime = time(NULL);
ctimestr = localtime(&ctime);
fprintf(fp,"%d,%04d-%02d-%02d %02d:%02d:%02d\n",linecount,
ctimestr->tm_year+1900,ctimestr->tm_mon+1,
ctimestr->tm_mday,ctimestr->tm_hour,
ctimestr->tm_min,ctimestr->tm_sec);
fflush(fp);
linecount++;
sleep(1);
}
fclose(fp);
}