免费注册 查看新帖 |

Chinaunix

广告
  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1593 | 回复: 2
打印 上一主题 下一主题

[C] 谁能指点一下这段代码如何改成迭代 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2010-09-25 14:02 |只看该作者 |倒序浏览
  1. int rm_rf_dir(char *src_path)
  2. {
  3.    DIR *dp;
  4.    struct dirent *dir;
  5.    struct stat st;
  6.    char file_path[312];
  7.    char msg_string[350];


  8.    if((dp = opendir(src_path)) == NULL)     
  9.      {
  10.            sprintf(msg_string,"ERRORS|Delete last month IndexDB %s error.\n",src_path);
  11.            writeLog(conf_data.Log_path,msg_string,1);
  12.        return (-1);
  13.      }
  14.      else
  15.      {
  16.        while((dir = readdir(dp)) != NULL)
  17.        {
  18.            if ( (strcmp(dir->d_name,".")!=0) && (strcmp(dir->d_name,"..")!=0) )
  19.            {
  20.                sprintf(file_path,"%s/%s",src_path,dir->d_name);
  21.                if((stat(file_path,&st))==0)
  22.                {
  23.                    if(S_ISREG(st.st_mode))
  24.                    {
  25.                        remove(file_path);
  26.                    }
  27.                    else if(S_ISDIR(st.st_mode))
  28.                    {
  29.                        rm_rf_dir(file_path);
  30.                        rmdir(file_path);
  31.                    }
  32.                }
  33.            }
  34.        }
  35.        closedir(dp);
  36.        return (0);
  37.    }
  38. }
复制代码
自己写了一段递归删除文件夹下面的子目录及文件的代码(保留目录本身),哪位老大能指点一下怎样改成迭代。

论坛徽章:
0
2 [报告]
发表于 2010-09-25 14:11 |只看该作者
递归变迭代的话注意两点即可。保存函数入口值和修改了的局部值,在递归函数结束的时候恢复这些值。

论坛徽章:
0
3 [报告]
发表于 2010-09-25 14:24 |只看该作者
用代码模拟一下整个过程就好了。
BTW,用python的话也就十分之一的代码行数吧。
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP