免费注册 查看新帖 |

Chinaunix

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

遍历列出指定目录下面的前N个文件 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2009-01-05 17:04 |只看该作者 |倒序浏览
今天项目中碰到这样一个功能,当磁盘满后,按顺序删除磁盘中的前50个文件。在网上找了一下,有一些人写过,但是觉得好像有些问题,最后自己写了如下一个测试程序用来遍历指定目录下的前面N个文件。

#include stdio.h>
#include dirent.h>
#include sys/types.h>
#include sys/stat.h>
#define    FILENAME_LEN    128
void FreeNameList(struct dirent **namelist, int n)
{
    int i;
    for( i=0; in; i++)
        free(*(namelist+i));
    free(namelist);
}
int ListDir(unsigned char *path, unsigned char *tmpcmd, unsigned char delcnt);
int ListDir(unsigned char *path, unsigned char *tmpcmd, unsigned char delcnt)
{
    struct dirent **namelist;
    int i, total, total1;
    struct stat statbuf;
    char path1[FILENAME_LEN];
    char tmp[FILENAME_LEN];
    unsigned char deleted_cnt=0;
    static char nest=0;
    total = scandir(path, &namelist, 0, alphasort);
    //DBG("nest %d\n", ++nest);
    if( total  3)
    {
        FreeNameList(namelist, total);
        return 0;
    }
    i = 2;
    if( strncmp(namelist->d_name, "lost", 4) == 0)
        i ++;
    while((itotal)&& (deleted_cnt  delcnt) )
    {
        sprintf(tmp, "%s/%s", path, namelist->d_name);
        lstat(tmp, &statbuf);
        if( S_ISDIR(statbuf.st_mode) == 0)
        {
            //sprintf(tmpcmd, "rm %s/%s -f", path, namelist->d_name);
            //DoCommand(tmpcmd);
            printf("%s/%s\n", path, namelist->d_name);
            deleted_cnt++;
        }
        else
        {
            sprintf(path1, "%s/%s/", path, namelist->d_name);
            deleted_cnt += ListDir(path1, tmpcmd, delcnt-deleted_cnt);
        }
        i++;
    }
    FreeNameList(namelist, total);   
    //DBG("exit nest %d, deleted_cnt = %d\n", nest--, deleted_cnt);
    return deleted_cnt;
}
int main(int argc, char *argv[])
{
    unsigned char cmd[200];
    if( (argc != 3) || (strlen(argv[1])>64))
    {
        printf("Usage: listdir pathname cnt\n");
        return 0;
    }
    ListDir(argv[1], cmd, atoi(argv[2]));
    return 0;
}


本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u3/90574/showart_1775484.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

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

清除 Cookies - ChinaUnix - Archiver - WAP - TOP