功能:文件操作 获取时间函数 日志文件
编程读写一个文件log.txt每隔1秒向文件中写入一行记录(类似系统维护日志)类似于这样:
1 2012-8-10 19:42:36
2 2012-8-10 19:42:37
。。。。。。。
下次再启动程序时在test.txt文件末尾追加记录,并且编号连续。
代码:
#include <stdio.h>
#include <time.h>
#include <string.h>
int get_time_str(char *timestr)
{
char str[100]={0};
time_t t = time(0);
strftime(str, sizeof(str),"%Y-%m-%d %H:%M:%S",localtime(&t));
strcpy(timestr,str);
return 0;
}
int main()
{
char str[100]="0";
FILE * fp = fopen("time.txt","a");
if(fp == NULL)
{
perror("fopen");
return -1;
}
int i=1,n;
while(1)
{
get_time_str(str);
n=fprintf(fp,"%d %s\n",i,str);
i++;
sleep(1);
printf("%d %s\n",n,str);
}
fclose(fp);
return 0;
}
编译通过,运行:
23 2012-08-10 19:35:36
23 2012-08-10 19:35:37
23 2012-08-10 19:35:38
23 2012-08-10 19:35:39
23 2012-08-10 19:35:40
Vi time.txt
空白。。。。。。。。。。。没有写入?什么情况?n=23了呢··奇怪了
是不是格式化输入不能用空格?
修改
fprintf(fp,"%d %s\n",i,str);还是不行。
用这个代替 fwrite(array, sizeof(array), 1, fp);还是没写到文件里·····
求解。。。。。
我去,把sleep注释了竟然可以写入了···
结果:-rw-rw-r-- 1 huangbin huangbin 9764864 08-10 21:44 time.txt
运行不到一秒差不多写入十兆了。。。
没遇到过····
解决办法:
在sleep后加上fflush(fp);就可以了,这就涉及到缓冲的问题了,行缓冲,全缓冲还有无缓冲,没有刷缓冲的话它就一直在缓冲里存着,只有缓冲满的时候才写入。。。应该是这么回事~~