目录
题目:
编程读写一个文件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
思路:
- 打开文件fopen,循环往文件写内容
- 每隔1s写入一行,sleep(1);
- 计算文件行数,wc -l
- 计算当前时间,转换成年月日、时分秒,time,localtime
man 2 time
time_t time(time_t *t);
如果t是空指针,直接返回当前时间。如果t不是空指针,返回当前时间的同时,将返回值赋予t指向的内存空间。
man 3 localtime
struct tm *localtime(const time_t *timep);
返回值是结构体指针,所指结构体封装着年月日时分秒
代码:
#include <stdio.h>
#include <time.h>
#include <string.h>
#include <unistd.h>
int main(int argc, char const *argv[])
{
if (argc != 2)
{
printf("err:%s <filename>\n", argv[0]);
return -1;
}
//1.打开文件
FILE *fp = fopen(argv[1], "a+");
if (NULL == fp)
{
perror("fopen err");
return -1;
}
//2. 计算行数
char buf[32] = "";
int len = 0;
while (fgets(buf, 32, fp) != NULL)
{
if (buf[strlen(buf) - 1] == '\n')
len++;
}
//3. 循环把时间戳写入文件,1s一行
time_t t;
struct tm *tm;
while (1)
{
time(&t);
tm = localtime(&t);
fprintf(fp, "%d, %d-%d-%d %d:%d:%d\n", ++len, tm->tm_year + 1900,
tm->tm_mon + 1, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec);
sleep(1);
fflush(NULL);
}
return 0;
}