View Full Version : Plz help me to debug my program

04-02-2004, 03:06 AM
I write a program to search file or directory from current directory by user's input.
Below is my 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) {

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);

if (stat(dp->d_name, &sbuf) == -1) {
perror("stat()"); /* Has problem here */

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);
printf("\t%s%s\n", path, name);


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);

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!!!

04-02-2004, 01:54 PM
Why not print out the filename of what you're actually stat'ing.

if (stat(dp->d_name, &sbuf) == -1) {
Also, this
scanf("%s", &input);
should be
scanf("%s", input);
or even better, use fgets() but make sure you get rid of the newline character that fgets() puts into the buffer for you.

For sample code, see the FAQ