c - 编写我自己的查找程序时出现段错误

标签 c linux unix

所以只是澄清一下。这是学校作业。我们正在编写一个简化的查找程序 (sfind),但我遇到了一个问题。

基本上,-print 标志在任何没有大量可看的情况下都能完美工作。但是,当我尝试从我的基本目录(包含大量文件)运行它时,我最终遇到了段错误。我觉得这可能出于多种原因。

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

最佳答案

您对正在处理的每个文件 都有一个递归调用。调用堆栈会很快变深,你会溢出堆栈。

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

关于c - 编写我自己的查找程序时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44031792/

相关文章:

bash - 如何在 bash 命令替换中转义单引号字符

linux - 解压单文件挂起

c - 将文件打开到结构体中

linux - IN 指令段错误,内联汇编 GCC

python - 来自C,我应该如何学习Python?

linux - 解释这个命令 : . ~/nvm/nvm.sh

c -/proc 目录是根据请求动态生成的吗?

linux - 我可以将 Bash 提示符的输入颜色更改为与终端默认值不同的颜色吗?

c - 如何让我的随机函数工作?

c - 如何重置 scanf()