Reputation: 47
I am trying to count files of a directory and its subdirectories. But I am getting a seg fault every time and I don't see why.
I used the code from here: Counting the number of files in a directory using C
Thanks for help
#include <stdio.h> // use input/output functions
#include <string.h> // use string functions
#include <dirent.h> // use directory functions
int countFilesRec(char* dirName);
// Global variable
int countFiles = 0;
/** Count files and subdirectories in given directory. */
int main(int argc, char* argv[])
{
// Read parameters
if (argc != 2) {
printf("Usage: countFiles <directory>\n");
return -1;
}
// Count Files
printf(countFilesRec(argv[1]));
return 0;
}
int countFilesRec(char *path) {
DIR *dir_ptr = NULL;
struct dirent *direntp;
char *npath;
if (!path) return 0;
if( (dir_ptr = opendir(path)) == NULL ) return 0;
int count=0;
while( (direntp = readdir(dir_ptr)))
{
if (strcmp(direntp->d_name,".")==0 ||
strcmp(direntp->d_name,"..")==0) continue;
switch (direntp->d_type) {
case DT_REG:
++count;
if (strcmp(direntp->d_name,"arbeitspfad bsks.txt")==0){
count=count-1;
count=count+1;
}
//printf("%s\n",direntp->d_name);
break;
case DT_DIR:
npath=malloc(strlen(path)+strlen(direntp->d_name)+2);
sprintf(npath,"%s/%s",path, direntp->d_name);
//printf("%s\n",npath);
count += countFilesRec(npath);
free(npath);
break;
}
}
closedir(dir_ptr);
//printf(count);
return count;
}
Upvotes: 0
Views: 779
Reputation: 12988
printf
does not take an integer. It takes a format string and a variable list of arguments. Your problem can probably be fixed by changing:
// Count Files
printf(countFilesRec(argv[1]));
to
int fileCount = countFilesRec(argv[1]);
printf("File count = %d\n", fileCount);
The change stores the integer result of your function in a variable and then uses a suitable format string to print it.
Upvotes: 1