C程序:分段使用opendir和readdir时出错

时间:2015-02-10 00:20:02

标签: c unix directory system-calls

我正在编写一个简单的程序,打开您正在使用的当前目录并打印目录流的所有内容,然后通过命令行获取其他目录并打印其流的内容。问题是,当我通过命令行键入false目录时,我的程序无法打印“无法访问目录名”并给我“分段错误(核心转储)”

这是我的主类“myls.c”

#include <sys/types.h>
#include <errno.h>
#include <dirent.h>
#include <stdio.h>
#include "mylsFunctions.h"

int main (int argc, char *argv[]) {
        printDirectoryContents("./.");

        for( int i = 1; i<argc; i++)
                printDirectoryContents(argv[i]);
}

这是我的函数在Main“mylsFunctions.c”

中使用的文件
#include <dirent.h>
#include <stdio.h>  
#include <sys/types.h>
#include <stdlib.h>
#include "mylsFunctions.h"

void printDirectoryContents (char *directory) {
    currentDirectory = opendir(directory);
    if(currentDirectory == NULL) {                         
            printf("Cannot Access %s",directory);
            exit(-1);
    }
    while ((entry=readdir(currentDirectory)) != NULL)
            printf("%s\n",entry->d_name);
    closedir(currentDirectory);
}

这是标题“mylsFunctions.h”

#ifndef MYLSFUNCTIONS_H
#define MYLSFUNCTIONS_H

DIR *currentDirectory;
struct dirent *entry;

void printDirectoryContents(char *directory);
#endif

0 个答案:

没有答案