I wrote a simple function to count the number of non-hidden files in a directory. However I noticed that when I used ++
to increment the count value I got weird results, like negative numbers and really large numbers. When I switch the line *count++;
to *count = *count + 1;
the function behaves as I expected. Can someone explain this behavior?
To use this example program pass the path to the directory as the first argument.
#include <stdio.h>
#include <dirent.h>
int count_files_directory(unsigned int *count, char *dir_path)
{
struct dirent *entry;
DIR *directory;
/* Open the directory. */
directory = opendir(dir_path);
if(directory == NULL)
{
perror("opendir:");
return -1;
}
/* Walk the directory. */
while((entry = readdir(directory)) != NULL)
{
/* Skip hidden files. */
if(entry->d_name[0] == '.')
{
continue;
}
printf("count: %d\n", *count);
/* Increment the file count. */
*count++;
}
/* Close the directory. */
closedir(directory);
return 0;
}
int main(int argc, char *argv[])
{
int rtrn;
unsigned int count = 0;
rtrn = count_files_directory(&count, argv[1]);
if(rtrn < 0)
{
printf("Can't count files\n");
return -1;
}
return 0;
}