将时间打印到一个文件并打印行号

#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;
}

posted @ 2020-12-17 22:14  ding-ding-light  阅读(107)  评论(0编辑  收藏  举报