0
点赞
收藏
分享

微信扫一扫

滚雪球学Redis[7.4讲]:Redis在分布式系统中的应用:微服务与跨数据中心策略

E_topia 2024-11-05 阅读 2

问题:显示指定目录下的 .c 文件

算法:

        1. opendir ( ) 打开文件夹

        2. readdir ( ) 读取文件名

        3. 通过字符串比对找出 .c 文件并打印输出

        4. closedir ( ) 关闭文件夹

代码:

#include<stdio.h>
#include<sys/types.h>
#include<dirent.h>
#include<string.h>

int main(int argc,char* argv[]){
    DIR *pd = NULL;
    struct dirent *pitem = NULL;
    char *p = NULL;
    int len = 0;
    if(argc < 2){
        printf("The argument is too few.\n");
        return 1;
    }
    pd = opendir(argv[1]); // 打开文件夹
    pitem = readdir(pd); // 读取
    while(pitem != NULL){
        if(pitem->d_type == DT_REG){ // 如果是常规文件
            len = strlen(pitem->d_name); // 获取文件名长度
            if(len >= 2){
                p = pitem->d_name + len - 1 - 1;// 定位到倒数第二个字符
                if(strcmp(p,".c") == 0) // 找出文件结尾是.c的文件
                    printf("%s\n",pitem->d_name); // 打印输出
            }
        }
        pitem = readdir(pd);
    }

    closedir(pd);
    pd = NULL;

    return 0;
}

输出:

p.s. 省略 gcc 编译过程   , ./ 表示 当前文件夹

举报

相关推荐

0 条评论