Linux中使用glib库函数实现递归获取具有特定扩展名的文件

#include <glib.h>

int file_filter(gchar *dir_name,gchar * suffix)
{
if(!g_file_test(dir_name,G_FILE_TEST_IS_DIR)||g_file_test(dir_name,G_FILE_TEST_IS_SYMLINK))
{
g_printf("Abandoned!\n");
return 1;
}
GDir *dir;
if(!(dir = g_dir_open(dir_name,0,NULL)))
{
g_printf("Directory Opened Error!\n");
return 1;
}
gchar *abs_path = NULL;
const gchar *filename;
while(filename = g_dir_read_name(dir))
{
abs_path = g_strjoin("/",dir_name,filename,NULL);
if(g_file_test(abs_path,G_FILE_TEST_IS_DIR)&&!g_file_test(abs_path,G_FILE_TEST_IS_SYMLINK))
{
file_filter(abs_path,suffix);
}
else if(!g_file_test(abs_path,G_FILE_TEST_IS_SYMLINK)&&g_str_has_suffix(abs_path,suffix))
{
g_printf("%s\n",abs_path);
}

}
g_dir_close(dir);
g_free(abs_path);
}

int main(int argc,char *argv[])
{
if(argc != 2)
{
g_printf("Parameters Error!\n");
return 1;
}
file_filter(argv[1],"c");
return 0;
}

相关推荐