fwoncn
fwoncn

Reputation: 189

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

Here is some simple code:

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

What I get is kind of messy: including dot (.), dot-dot (..) and file names that end with ~.

I want to do exactly the same thing as the command ls. How do I fix this, please?

Upvotes: 6

Views: 23632

Answers (4)

Zifre
Zifre

Reputation: 27008

This is normal. If you do ls -a (which shows all files, ls -A will show all files except for . and ..), you will see the same output.

. is a link referring to the directory it is in: foo/bar/. is the same thing is foo/bar.

.. is a link referring to the parent directory of the directory it is in: foo/bar/.. is the same thing as foo.

Any other files beginning with . are hidden files (by convention, it is not really enforced by anything; this is different from Windows, where there is a real, official hidden attribute). Files ending with ~ are probably backup files created by your text editor (again, this is convention, these really could be anything).

If you don't want to show these types of files, you have to explicitly check for them and ignore them.

Upvotes: 17

Ankit
Ankit

Reputation: 1931

Eliminating hidden files:

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

Eliminating hidden files and files ending in "~":

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);
    }
}

Upvotes: 8

Zan Lynx
Zan Lynx

Reputation: 54355

Stick a if (cur->d_name[0] != '.') before you process the name.

The UNIX hidden file standard is the leading dot, which . and .. also match.

The trailing ~ is the standard for backup files. It's a little more work to ignore those, but a multi-gigahertz CPU can manage it. Use something like if (cur->d_name[strlen(cur->d_name)-1] == '~')

Upvotes: 3

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799230

This behavior is exactly like what ls -a does. If you want filtering then you'll need to do it after the fact.

Upvotes: 1

Related Questions