编程读写一个文件test.txt,每隔1秒向文件中写入一行时间信息
类似:
1, 2007-7-30 15:16:42
2, 2007-7-30 15:16:43
程序可以无限循环,直到ctrl^c结束循环
再次启动程序时可以追加到原文件之后,并且序号可以续接
比如
1, 2007-7-30 15:16:42
2, 2007-7-30 15:16:43
3, 2007-7-30 15:19:02
4, 2007-7-30 15:19:03
5, 2007-7-30 15:19:04
sleep(1);可以实现睡眠一秒
用time();函数可以获取系统当前时间,单位:秒,从1970-1-1到当前时间
time_t time(time_t *tloc); //*tloc = 时间, return 时间;
time_t t;
time(&t); //t = time(NULL);
localtime();//将时间秒数转换成年月日时分秒格式
struct tm *localtime(const time_t *timep);
struct tm *tm;
tm = localtime();将时间秒数转换成年月日时分秒格式
#include <stdio.h>
#include <unistd.h>
#include <time.h>
#include <string.h>
int main(int argc, char const *argv[])
{
FILE *fp;
//打开文件,不存在创建,存在追加,第一次读时流被定位到文件开头,写始终在末尾
fp = fopen("test.txt", "a+");
if (NULL == fp)
{
perror("");
return -1;
}
char buf[32] = "";
int count = 0;
time_t now;
struct tm *tms;
//行数追加
while (fgets(buf, 32, fp))
{
if (buf[strlen(buf) - 1] == '\n')
count++;
}
while (1)
{
now = time(NULL);
tms = localtime(&now);
count++;
//向buf中写入时间信息
sprintf(buf, "%d,%d-%d-%d %d:%d:%d\n", count, tms->tm_year + 1900, tms->tm_mon + 1, tms->tm_mday, tms->tm_hour, tms->tm_min, tms->tm_sec);
printf("%s\n", buf);//向终端输出
fputs(buf, fp);//向文件输出
fflush(NULL);//强制刷新缓存
sleep(1);//睡眠一秒
}
return 0;
}