文件操作问题,高人指导下
我要在程序中建立一文本文件,每隔一段时间就向里边写数据,和日志文件类似,求原代码我的系统为DOS7.11 PC/104开发平台
[解决办法]
void savefile(void *h,int len)
{
FILE *fp;
if((fp=fopen( "log.txt ", "ab "))==NULL) /*为输出打开一个二进制文件,如没有则建立*/
{
printf( "can not open file\n ");
exit(1);
}
fwrite(p,len,1,fp);/*写入一条记录*/
fclose(fp); /*关闭文件*/
printf( "-----save success!!-----\n "); /*显示保存成功*/
}
[解决办法]
既然时间间隔是固定的,
那么使用定时器触发即可。
下面的例子是定时接收数据,
把定时时间修改、接收数据改为写文件 即可。
=====================
//利用中断实现每500毫秒接收一次数据
//调用DOS下的中断。
//DOS的时钟中断 int 21H AH=0x1C 每秒产生18.2次中断
//该程序时间间隔为550毫秒 可以由count的值算出。
#include <stdio.h>
#include <dos.h>
#include <conio.h>
#define INTR 0X1C //0x1c为时钟中断
#ifdef __cplusplus
#define __CPPARGS ...
#else
#define __CPPARGS
#endif
void interrupt ( *oldhandler)(__CPPARGS);
int count=0;
int a=0,b=0;
struct time t;
void interrupt handler(__CPPARGS) // 执行DOS中断时调用的程序
{
count++;
if(count==10)
{ gettime(&t);
b=t.ti_hund;
printf( "(2) %d\n ",b);
if(b <a)printf( "Delay %d ms ",((100-a)+b)*10);
else printf( "Delay %d ms ",(b-a)*10);}
}
int main(void)
{
oldhandler = getvect(INTR); //取得原来的中断向量
setvect(INTR, handler); //设置现在的中断向量
gettime(&t);a=t.ti_hund;
printf( "(1) %d\n ",a);
while (count < 11); //循环等待。执行DOS的时钟中断
setvect(INTR, oldhandler); //执行完毕,恢复原来的中断向量
return 0;
}
[解决办法]
每隔一段时间
可以参考下面代码//每隔1秒打印一个递增的数字
void main()
{
time_t time1, time2;
static int i;
time( &time1 );
while(1)
{
time( &time2 );
if(time2 - time1 > 1)
{
time( &time1 );
printf( "%d\n ",i);
i++;
}
}
}