程序出错,你回滚了吗?

转载请加注:Qdieyou
请大家观察下以下代码片段:
FILE *fin;
FILE *fout;

fin = fopen("test.txt", "r");
if (fin == NULL) {
    return 0;
}
fout = fopen("good.txt","w");
if (fout == NULL) {
    return 0;
}

两次打开文件都进行了防错设计,但是却忽略了程序回滚,当fout打开文件出错时,在return之前,你是否忘了fin指针还是打开着呢?虽然这些可以在程序return后由系统来关闭,但显式的关闭已打开的资源是一个良好的编程习惯。

经过修改的良好代码如下:
FILE *fin;
FILE *fout;

fin = fopen("test.txt", "r");
if (fin == NULL) {
    return 0;
}
fout = fopen("good.txt","w");
if (fout == NULL) {
  fclose(fin);
    return 0;
}

类似的情况还有很多,比如说,两次申请内存,第二次申请失败,在返回时,记得把第一次申请的空间释放,以免造成内存遗漏。
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
1. 上线前的备份工作: 按日期生成上线记录文件夹 文件结构目录和正式环境保持一致 备份你所涉及到的修改文件 2. 上线前的准备工作: 把你修改到的patch文件 到 PATCH_ROOT 目录中 文件结构目录和正式环境保持一致 3. 上线工作: diff -r -b 比较 备份环境 和 发布环境 文件差异; 再次确定修改是否正确 PATCH_ROOT 下的文件夹和文件 发布到正式环境 即可; 完成上线后,要检查系统功能是否正确。 4. 回滚工作: BAK_ROOT 下的文件夹和文件 回滚到正式环境 即可 ; 完成回滚后 要检查系统功能是否正确回滚。 5. shell脚本功能: === 参数配置 ===: #指定正式环境的路径 正式环境的文件 WEB_ROOT=/var/www/html echo ${WEB_ROOT} #指定发布环境的路径 发布环境的文件 PAT_ROOT=/home/chenlong/blog echo ${PAT_ROOT} #指定发布管理日志的路径 记录发布过程,完成文件备份和文件patch PUB_ROOT=/home/chenlong/Publish === 使用方法 ===: #./apply.sh blog /home/chenlong/patch_sh/list20100520.txt 例如 -bash-3.2$ ./apply.sh blog /home/chenlong/patch_sh/list20100520.txt /var/www/html /home/chenlong/blog /home/chenlong/Publish blog /home/chenlong/patch_sh/list20100520.txt /home/chenlong/patch_sh === cmd === :/home/chenlong/patch_sh/apply_cp.sh /var/www/html/wp-includes/js/common.js /home/chenlong/Publish/blog/2010-05-21/bak /bin/cp /var/www/html/wp-includes/js/common.js /home/chenlong/Publish/blog/2010-05-21/bak/var/www/html/wp-includes/js/common.js === cmd === :/home/chenlong/patch_sh/apply_cp.sh /var/www/html/upload_editor.php /home/chenlong/Publish/blog/2010-05-21/bak /bin/cp /var/www/html/upload_editor.php /home/chenlong/Publish/blog/2010-05-21/bak/var/www/html/upload_editor.php === cmd === :/home/chenlong/patch_sh/apply_cp.sh /var/www/html/BM/Tpl/default/Admin/Img/index.php /home/chenlong/Publish/blog/2010-05-21/bak /bin/cp /var/www/html/BM/Tpl/default/Admin/Img/index.php /home/chenlong/Publish/blog/2010-05-21/bak/var/www/html/BM/Tpl/default/Admin/Img/index.php === cmd === :/home/chenlong/patch_sh/apply_cp.sh /home/chenlong/blog/wp-includes/js/common.js /home/chenlong/Publish/blog/2010-05-21/patch /bin/cp /home/chenlong/blog/wp-includes/js/common.js /home/chenlong/Publish/blog/2010-05-21/patch/home/chenlong/blog/wp-includes/js/common.js === cmd === :/home/chenlong/patch_sh/apply_cp.sh /home/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值