Linux标准I/O常用函数实例 向文件定时输出时间

Linux标准I/O实例 向文件定时输出时间

向文件每秒写入一次当前系统时间,并添加行号。下一次启动程序时自动在文本末追加时间。

涉及的函数

/*标准输出函数*/
int printf(const char *format, ...);
int fprintf(FILE *stream, const char *format, ...);
/*文件打开 读取函数*/
FILE *fopen(const char *path, const char *mode);
char *fgets(char *s, int size, FILE *stream);
/*获取系统时间函数*/
time_t time(time_t *t);
struct tm *localtime(const time_t *timep);
/*冲洗缓冲区函数*/
int fflush(FILE *stream);
/*休眠函数*/
unsigned int sleep(unsigned int seconds);

代码

#include <stdio.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
int main(int argc,char* argv[])
{

	FILE* fp;
	int line=0;
	char buf[64];
	time_t t;
	struct tm* tp;
	if(argc<2)
	{
		printf("Usage: %s <file>\n",argv[0]);
		return -1;
	}

	if((fp = fopen(argv[1],"a+"))==NULL)
	{
		perror("fopen\n");
		return -1;
	}

	while(fgets(buf,64,fp) != NULL) //计算有多少行。
	{
		if(buf[strlen(buf)-1] == '\n')line++;
	}

	while(1)
	{
		time(&t);
		tp = localtime(&t);
		fprintf(fp,"%02d, %d-%02d-%02d %02d:%02d:%02d\n",++line,tp->tm_year+1900,	tp->tm_mon+1,tp->tm_mday,tp->tm_hour,tp->tm_min,tp->tm_sec);
		fprintf(stdout,"%02d, %d-%02d-%02d %02d:%02d:%02d\n",line,tp->tm_year+1900,	tp->tm_mon+1,tp->tm_mday,tp->tm_hour,tp->tm_min,tp->tm_sec);
		
		fflush(fp);
		sleep(1);
	}
	return 0;
}

发布了18 篇原创文章 · 获赞 92 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_27350133/article/details/84308179