当我第二次调用它时,我自己的shell无法执行搜索

时间:2015-10-27 13:51:31

标签: c shell search directory

当我给我的贝壳' ls'作为第一个参数,它工作正常,但是当我第二次使用它时,没有终止shell,它既不能找到文件,也不能给我一个分段错误。我确定它与while循环有关。我尝试在函数结束时将i设置为0,但它没有工作。提前谢谢。

这是我的搜索功能

int searchForFile(int argc, char *argv[]) {
DIR* dir;           // Var for scanned directory.
struct dirent* entry;       // Var for one directory entry.
char* fileName = argv[0];

int i = 0;
char** directoryArray = tokenised(PATH);

while(directoryArray[i] != NULL) {
    printf("Searching directory: '%s'\n", directoryArray[i]);
    dir = opendir(directoryArray[i]);
    if(!dir) {
        perror("Can't open the directory");
        return 0;
    }

    while((entry = readdir(dir))) {
        //Compare the entry's name with fileName
        if(strcmp(entry->d_name, fileName) == 0) {
            printf("Found: Address is '%s/%s'\n", directoryArray[i], entry->d_name);
            //Form an address out 2 strings
            char *address = malloc(sizeof(char)*strlen(directoryArray[i])+sizeof(char)*strlen(entry->d_name)+2*sizeof(char));
            strcpy(address, directoryArray[i]);
            strcat(address, "/");
            strcat(address, fileName);
            argv[0] = address;
            i = 0;
            execute(argc, argv);

            //Free memory
            int j = 0;
            while(directoryArray[j] != NULL) {
                free(directoryArray[j]);
                j++;
            }
            free(directoryArray);
            //free(address);
            closedir(dir);
            return 1;
        }

    }
    closedir(dir);
    i++;
}
return 0;

0 个答案:

没有答案