I write a program to search file or directory from current directory by user's input.
Below is my code.
Code:
#include <stdio.h>
#include <unistd.h>
#include <dirent.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>

static int cnt = 0;

void in_dir(char *path, char *find) {
   DIR *dirp;
   struct dirent *dp;
   struct stat sbuf;
   char *name;
   char *new_path;
   
   dirp = opendir(path);
   if (!dirp) {
      perror("opendir()");
      return;
   }
   
   path = strcat(path, "/");
   new_path = path;
   
   while ((dp = readdir(dirp)) != NULL) {
      if (strstr(dp->d_name, find) == NULL) {
         if (S_ISDIR(sbuf.st_mode)) {
            in_dir(new_path, find);
         }
         continue;
      }
      
      if (stat(dp->d_name, &sbuf) == -1) {
         perror("stat()");                   /* Has problem here */
         return;
      }
      
      name = dp->d_name;
      if (S_ISDIR(sbuf.st_mode)) {
      	 new_path = strcat(new_path, name);
         printf("\t%s\n", new_path);
         in_dir(new_path, find);
      }
      else
         printf("\t%s%s\n", path, name);
      
      ++cnt;
   }
}

int main(int argc, char *argv[]) {
   char *cur_path;
   char buf[100];
   char input[10];
   
   printf("File or directory name you want to search: ");
   /*fgets(input, 10, stdin);*/
   scanf("%s", &input);
   
   /*printf("You wanna to search '%s'\n", input);*/
   /* Start to search from current directory. */
   cur_path = getcwd(buf, 100);
   in_dir(cur_path, input);
   
   printf("%d matches.\n", cnt);
   return(0);
}
If files are located in current directory, my program works well.
However, if files are located in sub-directory, my program goes to wrong.
The error message is :
stat(): No such file or directory
But I am sure the filename it passed to is exist.
I have no idea how to debug it.
Could anyone help me? Very thanks!!!