Please refer to the code below.It is used to extract files from a given directory, for further processing.

include <dirent.h>
include <stdio.h>
include <string.h>

int main(void)
{
int i=0;
struct dirent *direntry;
dir = opendir("E:/muzikk");
if(!dir)
{
printf("Error: directory did not open!\n");
return 1;
}
while((direntry=readdir(dir))!=NULL)
{

        printf("%d %s\n",i,direntry->d_name);
        i++;
}

closedir(dir);
    return 0;

}

The problem is,that on running, it returns the first two file names as '.'(on zero position) and '..'(on first position), which is undesirable. can anyone explain or help. thanks.

Dani AI

Generated

Short note building on , and : skipping every name that starts with . (as suggested by ) will hide dotfiles like .svn. A safer, minimal change is to skip the two special entries . and .. only, and—if needed—use stat() (portable) or d_type (where available) to process only regular files.

Example (portable, checks regular files):

#include <stdio.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>

int main(void)
{
    DIR *d = opendir("E:/muzikk");
    struct dirent *ent;
    char path[4096];
    int i = 0;

    if (!d) { perror("opendir"); return 1; }

    while ((ent = readdir(d)) != NULL) {
        if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0)
            continue;

        snprintf(path, sizeof(path), "E:/muzikk/%s", ent->d_name);
        struct stat st;
        if (stat(path, &st) == 0 && S_ISREG(st.st_mode)) {
            printf("%d %s\n", i++, ent->d_name);
        }
    }
    closedir(d);
    return 0;
}

Notes: d_type in struct dirent (DT_REG/DT_DIR) can avoid stat() on Linux/UNIX but is not guaranteed (some filesystems return DT_UNKNOWN). On Windows (MSVC) use FindFirstFile/FindNextFile or a dirent compatibility layer. Also use snprintf() to build paths safely. If the directory truly contains only plain text files (as said), the simple strcmp filter is enough and is the least surprising behavior.

Recommended Answers

All 3 Replies

That will always happen. '.' is the current directory and '..' is the parent directory.

while((direntry=readdir(dir))!=NULL)
{
    // If the first character is a dot, then skip it
    if ( direntry->d_name[0] == '.' )
       continue;
    printf("%d %s\n",i,direntry->d_name);
    i++;
}
closedir(dir);
Member Avatar for Member #907664

// If the first character is a dot, then skip it

That will work, but not 100% of the time. It would fail if you had a directory named .svn, for example.

ya..but thats alright for me since the directory contains only text files.Thanks.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.