c语言连续存储文件中断

  在计算数值模拟的时候,经常需要将上一步计算得出值来作为下一步的输入,进行迭代计算,如果数值过多,需要分析每一步的中间值,将每一步的值保存下来,存储到硬盘上。于是问题就产生了。

环境:1.编程语言:C

            2.编译环境:VS2010

            3.系统环境:XP,Win7

程序主体如下:

#include "stdafx.h"
#include <stdio.h>
#include <Windows.h>
int _tmain(int argc, _TCHAR* argv[])
{
	double calValue = 0;//the initial value
        int calTimes = 10;//the calculate times
        int iCount = 0;
	while (calTimes--)
	{
		//this place, just for show, in the actual, the calculate express may be complex and a lot of values should be saved.
		calValue = calValue + 1 ;
		char savePath[128] = {0};
		sprintf(savePath,"D:\\test\\%0.4d.txt", ++iCount);
		FILE *pFlie = fopen(savePath, "w");
		if (pFlie)
		{
			fprintf(pFlie,"%f\n", calValue);
			fclose(pFlie);
                        pFile = NULL;
                }
	}
	return 0;
}

问题1:不小心点了关闭程序按钮,怎样让程序启动时接着原来的步骤进行。

解决方案:记录存储的文件的序号,从上次文件中读取数据开始余下的计算。代码如下:

int _tmain(int argc, _TCHAR* argv[])
{

	double calValue = 0;//the initial value
	int calTimes = 10;//the calculate times
	int iCount = 0;

	//add another file to record the num of current process
	FILE *pRecord = NULL;
	pRecord = fopen("D:\\test\\record.txt","r");
	if (pRecord)
	{
		fscanf(pRecord, "%d", &iCount);
		fclose(pRecord);
		pRecord = NULL;
	}

	char savePath[128] = {0};
	sprintf(savePath,"D:\\test\\%0.4d.txt", iCount);
	FILE *pFile = fopen(savePath, "r");
	if (pFile)
	{
		fscanf(pFile, "%lf", &calValue);
		fclose(pFile);
		pFile == NULL;
	}

	//this time, calTimes will subtract the iCount
	calTimes = calTimes - iCount;
	printf("now we begin from iCount = %d\n", iCount);
	while (calTimes--)
	{
		//this place, just for show, in the actual, the calculate express may be complex and a lot of values should be saved.
		calValue = calValue + 1 ;
		char savePath[128] = {0};
		sprintf(savePath,"D:\\test\\%0.4d.txt", ++iCount);
		printf("now we begin save file %s", savePath);
		FILE *pFlie = fopen(savePath, "w");
		if (pFlie)
		{
			fprintf(pFlie,"%f\n", calValue);
			fclose(pFlie);
			pFlie = NULL;
		}
		printf("end save\n");
		//because i want to see the effect, so sleep 1 second
		Sleep(1000);

		printf("now we begin record\n");
		FILE *pRecord = NULL;
		pRecord = fopen("D:\\test\\record.txt","w");
		if (pRecord)
		{
			fprintf(pRecord, "%d", iCount);
			fclose(pRecord);
			pRecord = NULL;
		}
		printf("end record\n");
	}
	return 0;
}
问题2:现在改变条件,假如需要更新某一个文件,当更新到一半时,程序退出,如何进行处理。

解决方案:备份原文件,修改当前文件,更新完成,则删除备份文件;更新未完成,则删除当前文件,将备份拷贝为当前文件。

        通过SetConsoleCtrlHandler()设置消息回调函数,捕获程序退出响应,判断文件是否更新完成,做相应的处理。


问题3:接着问题2的情况,突然断电了,文件未更新完毕。

解决方案:在启动程序时,进行检测,如果存在备份文件,则删除当前文件,采用备份文件。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值