#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <time.h>
#include <stdlib.h>
int get_line()
{
int line = 1;
FILE *file1 = fopen("./time1.txt", "r");
char *buf = calloc(32, sizeof(char));;
while(fgets(buf, 32, file1) != NULL)
{
if (buf[strlen(buf)-1] == '\n')
line++;
}
printf("%d\n", line);
return line;
}
int main(int argc, char const *argv[])
{
time_t timep;
char *buf;
char *file_name = "./time1.txt";
int fd = open(file_name, O_WRONLY | O_APPEND );
int i = get_line();
while(1)
{
time (&timep);
char tmp[32];
buf = asctime(gmtime(&timep));
sprintf(tmp,"[%d]%s",i, buf);
sleep(1);
int ret = write(fd, tmp, strlen(tmp));
printf("ret:%d\n", ret);
if (ret == -1)
{
printf("write %s error , msg: %s\n" , file_name, strerror(errno));
}
fsync(fd);
memset(tmp, '\0', 32);
i++;
}
return 0;
}
![](https://img2020.cnblogs.com/blog/2228564/202012/2228564-20201217221528007-2008799047.png)