#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/types.h>
#include <string.h>
#ifndef oj_dir
#define oj_dir "/home/rain/oj"
#endif
//取出目录中.in文件
//参数中,dir是要查询的目录,in_files数组保存每个.in文件,函数返回所有.in文件个数
int printdir(char *dir, char* in_files[])
{
DIR *dp;
struct dirent *entry;
if ((dp = opendir(dir)) == NULL)
{
fprintf(stderr, "cannot open directory: %s\n", dir);
return 0;
}
chdir(dir);
int in_file_num = 0;
char dir_prefix[20], dir_suffix[20];
while((entry = readdir(dp)) != NULL)
{
/* ignore . and .. ,分别代表当前目录和上一级目录*/
if (strcmp(".", entry->d_name) == 0 || strcmp("..", entry->d_name) == 0)
{
continue;
}
sscanf(entry->d_name, "%[^.].%[^.]", dir_prefix, dir_suffix);
if (strcmp("in", dir_suffix) == 0)
{
in_files[in_file_num ++] = entry->d_name;
}
}
chdir(oj_dir);
closedir(dp);
return in_file_num;
}
int main(int argc, char const *argv[])
{
char* in_files[10];
int in_file_nums = printdir("/home/rain/data/1001", in_files);
printf("%d\n", in_file_nums);
int i;
for (i = 0; i < in_file_nums; ++i)
{
printf("%s\n", in_files[i]);
}
return 0;
}
目录如下:
rain@HY:~/oj$ gcc get_file_with_same_suffix.c -o get_file_with_same_suffix
rain@HY:~/oj$ ./get_file_with_same_suffix
4
data.in
data3.in
data4.in
data2.in