How to ignore hidden files using opendir and readdir in C library

Here is a simple code:

DIR* pd = opendir(xxxx);
struct dirent *cur;
while (cur = readdir(pd)) puts(cur->d_name);

What I get is rather messy: including dot ( .), dot-to-dot ( ..), and file names ending in ~.

I want to do the same thing as the team ls. How to fix this please?

+5
source share
4 answers

This is normal. If you execute ls -a(which shows all files, it ls -awill show all files except .and ..), you will see the same result.

.- a link related to the directory in which it is located: foo/bar/.- this is the same as foo/bar.

.. - , , : foo/bar/.. - , foo.

, ., ( , , Windows, , ). , ~, , , ( , , ).

, .

+15

:

DIR* pd = opendir(xxxx);
struct dirent *cur;
while (cur = readdir(pd)) {
    if (cur->d_name[0] != '.') {
        puts(cur->d_name);
    }
}

, "~":

DIR* pd = opendir(xxxx);
struct dirent *cur;
while (cur = readdir(pd)) {
    if (cur->d_name[0] != '.' && cur->d_name[strlen(cur->d_name)-1] != '~') {
        puts(cur->d_name);
    }
}
+6

if (cur->d_name[0] != '.'), .

UNIX , . ...

Ultimate ~is the standard for backup files. It is a bit more to ignore them, but a multi-gigahertz processor can control it. Use something likeif (cur->d_name[strlen(cur->d_name)-1] == '~')

+2
source

This behavior is exactly what it does ls -a. If you want to filter, you will need to do this after the fact.

+1
source

All Articles