我正在编写的这个 C 程序有一个奇怪的问题,我要循环遍历一个目录并打开每个文件来做一些工作。我的程序位于我正在搜索的目录的父目录中。为了让 fopen 能够看到该目录中的文件,我正在调用 while((dp = readdir(dfd)) != NULL) 之前进行 chdir(path) 调用。第一个文件被很好地拾取,但我在这个调用的下一次迭代中得到了一个段错误。chdir 和 readdir 逻辑似乎有问题,我不知道如何解决它。有任何想法吗?这是我的代码:
if((dfd = opendir(dir)) == NULL){
fprintf(stderr, "Can't open %s\n", dir);
return 0;
}
chdir(dir);
char *filename;
//loop through the directory
while((dp = readdir(dfd)) != NULL){
printf("Searching file %s\n", dp->d_name);
filename = malloc(50);
filename = dp->d_name;
char text[80];
int words = 0;
int cellular = 0, CDMA = 0, GSM = 0, LTE = 0, wireless = 0, realtime = 0, GPS = 0, remote = 0, monitor = 0;
struct stat stbuf;
//Skip any directories
if((stbuf.st_mode & S_IFMT) == S_IFDIR){
printf("Directory skipped.\n");
continue;
}
//Skip files that can't be opened
if((fpt=fopen(filename,"r")) == NULL){
printf("Couldn't open file %s.\n", filename);
continue;
}
//search the file
while(fscanf(fpt, "%s", text) != EOF){
words++;
//....etc