abhijangda
Padawan
Hello friends, I am creating C program that will list all the files in the directory specified with their paths. So code is here.
Here declevel is a function (or more specifically procedure) that will decrease the path string with level 1. I mean if path string is /media/sda1/downloads then after calling declevel this path string will be /media/sda1. It runs very well when I run it independently in another program. But here I am getting error. Compiler (gcc) compiles it without error, but when I run it in terminal I got error segmentation fault (core dumped). Please help me friends.!!!

Code:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<dirent.h>
#include<sys/stat.h>
void declevel(char str[])
{
int count=0;
int i=0,j=0;
for (i=0;i<strlen(str);i++)
{
if (str[i] == '/')
{
count++;
}
}
int arr[count];
for (i=0;i<strlen(str);i++)
{
if (str[i] == '/')
{
arr[j] = i;
j++;
}
}
str[arr[count-1]] = '\0';
printf("%s",str);
}
void getdirstruct(char dir[])
{
DIR *dp;
struct dirent *entry;
struct stat statbuf;
char path[1000], path2[1000];
int s;
if ((dp = opendir(dir)) == NULL)
{
return;
}
chdir(dir);
strcat(path,dir);
while ((entry = readdir(dp)) != NULL)
{
lstat(entry->d_name,&statbuf);
if (S_ISDIR(statbuf.st_mode))
{
if (strcmp(".",entry->d_name) == 0 || strcmp(".", entry->d_name) == 0)
{
s = sprintf(path2,"%s",path);
declevel(path2); /*directory level decreases*/
continue;
}
getdirstruct(entry->d_name);
strcat(path,entry->d_name);
}
}
chdir(".");
closedir(dp);
}
void main()
{
getdirstruct("/home");
}

