思路:
1. 用 fopen 函数以追加的方式打开文件;
2. 用 frets 函数统计文件行数,在这个步骤中使用 strlen 来看 buf 缓冲区里面的有效字符长度,读取完之后为了避免缓冲区中下一行读取的字符数小于当前行中读取的字符数,造成覆盖不全的情况,这里使用 memset 函数在每次读取完后,清空缓冲区;
3.获取时间,把行数和时间每隔1s往文件中写入数据;这里使用 localtime 函数来获取时间。
#include <stdio.h>
#include <time.h>
#include <string.h>
#include <unistd.h>
int main()
{
int line = 0;//定义行数
time_t t;//定义时间
//1.打开文件
FILE *fp = fopen("1.txt", "a+");
if(NULL == fp)
{
perror("fopen");
return -1;
}
//2.统计文件行数
char buf[64] = {0};
while(fgets(buf, 64, fp) != NULL)//读到有效数据,再继续下面的操作
{
if(buf[strlen(buf)-1] == '\n')//计算有效字符个数
if(buf[strlen(buf)-1] == '\n')//计算有效字符个数
{
line++;
}
memset(buf, 0, 64);//每读完一行,清空缓冲区
}
//3.获取时间,把行数和时间每隔1s往文件中写入数据
struct tm *m_t= NULL;
while(1)
{
time(&t);
m_t = localtime(&t);//用m_t接收
fprintf(fp, "%d %d年%d月%d日 %d:%d:%d\n", ++line, m_t->tm_year+1900, m_t->tm_mon+1, m_t->tm_mday, m_t->tm_hour, m_t->tm_min, m_t->tm_sec);
fflush(fp);//如果不加这一行,该文件默认全缓冲,当缓冲区满才能显示写入的数据
sleep(1);//延时1s
}
return 0;
}
1.txt中运行前的内容:
hello world
hello world
hello world
hello world
hello world
运行后1.txt运行后的内容:
hello world
hello world
hello world
hello world
hello world
6 2022年8月9日 4:35:8
7 2022年8月9日 4:35:9
8 2022年8月9日 4:35:10
9 2022年8月9日 4:35:11