Reputation: 3402
I wrote a small function that receives a path of a folder and should return the number of files inside it.
For some reason my answer is not correct: When printing it I saw that it prints .
and ..
.
Can someone tell me why? Would decreasing 2
solve it?
Here is the code:
{
struct dirent *entry;
DIR *dirp;
int fileCount = 0;
char currPath[MAX_STR];
dirp = opendir(clientLocalPath);
printf(" ***** printing files!!!!! ********\n");
while((entry = readdir(dirp)) != NULL)
{
strcpy(currPath, entry->d_name);
printf("%s\n",currPath);
fileCount++;
}
closedir(dirp);
return fileCount;
}
Upvotes: 1
Views: 121
Reputation: 4395
.
is the current directory
..
is the parent directory
These 2 names you will find in every folder while scaning for file. while getting files name you can ignore these two values by checking names in your code.
For example
"..\tmp.txt"
specifies a file named tmp.txt
located in the parent of the current directory
Upvotes: 2
Reputation: 290515
This is normal and it happens because both .
and ..
are part of the directories: .
refers to the current one and ..
to the parent.
From What is a dot only named folder?:
Every directory contains a
.
and a..
entry.
.
means the directory itself. It is called the current directory.
..
means the directory's parent directory, that is, the directory that contains it.
From Why do directory listings contain the current (.) and parent (..) directory?:
Best way is to just
strcmp
and ignore them, if you don't want to list them.
Upvotes: 1
Reputation: 2382
This behaviour is perfectly normal. The .
and ..
indicate current and parent directories respectively. If you want to ignore them and consider the rest of the files for your fileCount variable, you can do something like this:
while((entry = readdir(dirp)) != NULL)
{
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
printf("\0");
else
{
strcpy(currPath, entry->d_name);
printf("%s\n",currPath);
fileCount++;
}
}
Upvotes: 2