我正在编写一个简单的程序,打开您正在使用的当前目录并打印目录流的所有内容,然后通过命令行获取其他目录并打印其流的内容。问题是,当我通过命令行键入false目录时,我的程序无法打印“无法访问目录名”并给我“分段错误(核心转储)”
#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]);
}
#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);
}
#ifndef MYLSFUNCTIONS_H
#define MYLSFUNCTIONS_H
DIR *currentDirectory;
struct dirent *entry;
void printDirectoryContents(char *directory);
#endif
〜