linux环境使用c语言获取当前目录下有哪些文件,并打印它们的名字

代码: 

#include <sys/types.h>
#include <dirent.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>

void ReadDir(void)
{
    DIR *dir;
    struct dirent *ptr;
    int i = 0;
    char ch = '0';
    int result = 0;
    char buf[32] = {0};

    dir = opendir("./video/");
    while((ptr = readdir(dir)) != NULL)
    {
        if (strcmp(ptr->d_name, ".") == 0 || strcmp(ptr->d_name, "..") == 0)
        {
            continue;
        }
        if (ptr->d_type == DT_REG)
        {
            i = 0;
            result = 0;
            printf("d_name:%s\n", ptr->d_name);
            memset(buf, 0, 32);
            strcpy(buf, ptr->d_name);
            while(1)
            {
                ch = buf[i];
                if (ch == '_')
                {
                    break;
                }
                result = result*pow(10,i) + (ch-'0');
                i++;
            }
            printf("result = %d\n", result);
        }
    }
    closedir(dir);
}
int main(void)
{
    ReadDir();
}

执行结果:

guoyanzhang@debian:~/from_share$ gcc test_dir.c -lm
guoyanzhang@debian:~/from_share$ ./a.out
d_name:3_a.c
result = 3
d_name:4_a.c
result = 4
d_name:2_a.c
result = 2
d_name:6_a.c
result = 6
d_name:18_12_12_dd.c
result = 18
d_name:19_13_12_dd.c
result = 19
d_name:7_a.c
result = 7
d_name:5_a.c
result = 5
d_name:11_a.c
result = 11
d_name:17_19_a_12.c
result = 17
d_name:10_a.c
result = 10
d_name:20_12_12_ff_gg.c
result = 20
d_name:16_di_f_g_d.c
result = 16
d_name:9_a.c
result = 9
d_name:8_a.c
result = 8
d_name:14_a_e.c
result = 14
d_name:13_a_d.c
result = 13
d_name:12_a_b.c
result = 12
d_name:1_a.c
result = 1
d_name:15_a_f_g.c
result = 15

 

已标记关键词 清除标记
相关推荐