Segmentation fault code

发表于:2007-07-04来源:作者:点击数: 标签:
不经意这出现Segmentation fault!! #include include/myhdr.h int prin td ir (char *, int); int main (int argc, char **argv) if (argc != 2) printf (Usage:listdir2 pathname\n); exit (2); //printf (%s\n, argv[1]); printdir (argv[1], 0); exit (0);
不经意这出现Segmentation fault!!

#include "include/myhdr.h"

int printdir (char *, int);

int
main (int argc, char **argv)
{
  if (argc != 2)
    {
      printf ("Usage:listdir2 <pathname>\n");
      exit (2);
    }

  //printf ("%s\n", argv[1]);
  printdir (argv[1], 0);

  exit (0);

}

int
printdir (char *dirpath, int depth)
{
  struct dirent *mydirent;
  DIR *mydir;
  struct stat *mystat;
  char pathbuf[35];

  if ((mydir = opendir (dirpath)) == NULL)
    {
      perror ("Open dir error:");
      exit (1);
    }
  //chdir (dirpath);

  while ((mydirent = readdir (mydir)) != NULL)
    {
      if (strcmp (mydirent->d_name, "..") == 0
   || strcmp (mydirent->d_name, ".") == 0)
 {
   continue;
 }

      pathbuf[0] = '';
      strcat (pathbuf, dirpath);
      strcat (pathbuf, mydirent->d_name);
      //printf ("pathbuf:%s\n", pathbuf);

      //if (lstat (mydirent->d_name, mystat) == -1)
      if (lstat (pathbuf, mystat) == -1)
 {
   perror ("stat file error:");
   exit (2);
 }

      if (S_ISDIR (mystat->st_mode))
 {
   printdir (pathbuf, depth + 4);
 }
      else
 {
   printf ("filename:%s,inode:%ld %d\n", mydirent->d_name,
    mydirent->d_ino, mystat->st_blksize);
 }   //if S_ISDIR end   
    }    //while end
  closedir (mydir);
  //chdir ("..");
  return 0;
}

原文转自:http://www.ltesting.net