2017-05-17 34 views
2

所以只是为了澄清。这是一个学校作业。我们正在编写一个简化的查找程序(sfind),并且我遇到了一个问题。编写我自己的查找程序时出现Seg错误

基本上,在任何情况下,-print标志都可以在任何情况下都可以完美地工作,因为这种情况下没有太多的数据可以查看。但是,当我尝试从我的基目录(其中有大量文件)运行它时,我最终遇到了seg故障。我觉得这可能是由于许多原因。

  1. 我的用户进程限制太低
  2. 我的最大文件大小太低
  3. 我得到堆栈溢出了太深的递归
  4. 我俯瞰
一些其他的事情

我在ubuntu上运行它,它将事件彻底地在Unix服务器上运行。

这是我目前的递归代码。

int printHelper(struct dirent *entry, DIR *dir, char* path){ 
    struct stat fileStat; 
    DIR *tempDir; 
    char tempPath[1000]; 
    char const* name = entry->d_name; 
    strcpy(tempPath, path); 
    strcat(tempPath, name); 
    lstat(tempPath, &fileStat); 
    if(strcmp(name, ".") != 0 && strcmp(name, "..") != 0){ 
     printf("%s%s\n", path, name); 
    } 
    if((S_ISDIR(fileStat.st_mode)) && (strcmp(name, ".") != 0) && (strcmp(name, "..") != 0)){ 
     struct dirent *tempEntr; 
     char newTempPath[1000]; 
     char newPathName[1000]; 
     strcpy(newPathName, name); 
     strcpy(newTempPath, path); 
     strcat(newTempPath, newPathName); 
     strcat(newTempPath, slashPath); 
     tempDir = opendir(newTempPath); 
     tempEntr = readdir(tempDir); 
     printHelper(tempEntr, tempDir, newTempPath); 
     closedir(tempDir); 
    } 
    if(!(entry = readdir(dir))){ 
      return 0; 
    } 
    printHelper(entry, dir, path); 
    return 0; 
} 

这里是文件

#include <sys/stat.h> 
#include <sys/resource.h> 
#include <sys/time.h> 
#include <unistd.h> 
#include <sys/types.h> 
#include <dirent.h> 
#include <stdio.h> 
#include <string.h> 
#include "myPrint.h" 

char slashPath[3] = "/\0"; 

int myPrint(char const* myFile){ 
    DIR *dir; 
    struct dirent *entry; 

    int isDir; 
    isDir = 1; 

    if (!(dir = opendir(myFile))){ 
     isDir = 0; 
    } 
    else if (!(entry = readdir(dir))){ 
     return -1; 
    } 
    if(isDir == 0){ 
     dir = opendir("."); 
     while((entry = readdir(dir))){ 
      if(strcmp(myFile, entry->d_name) == 0){ 
       printf("%s\n", myFile); 
       return 0; 
      } 
     } 
     printf("find: ‘%s’: No such file or directory\n", myFile); 
     return 0; 
    } 
    else{ 
     char path[2000]; 
     strcpy(path, myFile); 
     strcat(path, slashPath); 
     printf("%s\n", myFile); 
     printHelper(entry, dir, path); 
     return 0; 
    } 
    return 0; 
} 
+0

因为你没有基础案例 –

+0

你能澄清一点吗?因为代码更多。我将在 – Joe

+0

中编辑它使用调试器的时间。 – Olaf

回答

0

的开始你有一个递归调用每一个文件你正在处理。调用堆栈会变得很快,你会溢出堆栈。

更改代码以递归到每个目录而不是每个文件。让函数只接受一个目录路径。然后打开目录并使用while循环遍历每个条目。如果条目是目录,则,然后使用子目录的名称进行递归调用。

+0

嗯,所以你的意思是,最后当我打电话给自己的打印助手与它最初调用的所有相同的东西,而不是做一个while循环?我认为这是有道理的 – Joe

+0

@Joe不只是结束。通过调用'opendir'来启动函数,然后使用'while((entry = readdir(dir))!= NULL)'读取条目,然后使用'closedir'结束。 – dbush

+0

是的,我现在已经明白了。非常感谢。我被严重的难住了。 – Joe

相关问题