Scandir拥有过滤功能

时间:2016-06-22 15:08:42

标签: c linux scandir

我必须写2个函数,filter - names> 5个字符,我必须按类型对它们进行排序。

Filtr函数应该是这样的吗?

int (* filter) (const struct dirent* entry) {

    if ( (strlen(entry>d_name) - 1 ) > 5 ) {
        return entry;
    }
}

如何排序,直接指向它的dirent-> d_type,但如何排序?

1 个答案:

答案 0 :(得分:1)

您是否考虑过查看man 3 scandir页面?

(我发现Linux man-pages project手册页最适合C库和系统级编程。)

如果我们有一个需要调用者指定辅助函数的函数,我们的函数应该调用它来执行某个任务,我们将它声明为函数指针。换句话说,虽然scandir()函数的原型是

int scandir(const char *dirp, struct dirent ***namelist,
            int (*filter)(const struct dirent *),
            int (*compar)(const struct dirent **, const struct dirent **));

过滤器和比较函数的原型实际上是

int myfilter(const struct dirent *);
int mycompar(const struct dirent **, const struct dirent **);

功能的愚蠢实现(不符合您的运动要求)可以是例如

int myfilter(const struct dirent *entry)
{
    /* man 3 scandir says "entries for which filter()
     * returns nonzero are stored".
     *
     * Since file names in Linux are multibyte strings,
     * we use mbstowcs() to find out the length
     * of the filename in characters.
     *
     * Note: strlen() tells the filename length in bytes,
     *       not characters!
    */
    const size_t len = mbstowcs(NULL, entry->d_name, 0);

    /* Keep filenames that are 3 or 7 characters long. */
    return (len == 3) || (len == 7);
}

int mycompar(const struct dirent **entry1, const struct dirent **entry2)
{
    const size_t len1 = mbstowcs(NULL, (*entry1)->d_name, 0);
    const size_t len2 = mbstowcs(NULL, (*entry2)->d_name, 0);

    /* Compare by file name lengths (in characters),
     * sorting shortest file names first. */
    return (int)((ssize_t)len1 - (ssize_t)len2);
}

使用POSIX.1-2008编写代码时,请记得添加

#define _POSIX_C_SOURCE 200809L
在任何#include之前

。为了使您的代码在不同的环境中正常工作(例如,在文件名中计算字符而不是字节,在我们世界的任何Linux系统中),还{{1} },并添加

#include <locale.h>
在您阅读/扫描或写入/打印任何内容之前,在setlocale(LC_ALL, "");

。 (虽然还有更多的可以做更多的本地化程序,但上面经常就足够了。处理文本文件应该使用宽字符串(main())和{{1字符串和字符的类型和L"This is a ωide §tring liteℛal "类型,具有宽字符串I / O函数。它比在愚蠢的“二十七”中做的更复杂或难以做到ASCII字母对每个人来说都足够了,即使它以你的母语“方式将你的名字变成一个脏词。

如果你的老师没有提到这些,你应该问为什么。正确地无法处理文件或文本wchar_t的程序在当今时代是不可接受的。在学习正确的方法之前,没有必要首先学习错误的方式来做事,因为正确的方法就像错误的方式一样容易。