【发布时间】:2015-07-06 23:15:16
【问题描述】:
我在 while 循环结束时遇到分段错误(我不确定错误是在终止之后还是之前出现)。
我检查了dirlist_next_entry 之后成功返回DIRLIST_END
到达目录流的末尾。我不明白是什么导致了错误,因为循环应该在流结束后成功终止
#include "DirEntry.h"
#include <cstdio>
int main(int argc, char* argv[]){
if(argc != 2){
printf("Directory not specified\n");
return -1;
}
DirListError error;
DirEntry result;
handle hfile = dirlist_start_find(argv[1], &error);
while( dirlist_next_entry(hfile, &result) != DIRLIST_END){
printf("%s %lld\n", result.entry, result.size);
}
dirlist_end_find(hfile);
}
这里是dirlist_next_entry的定义:
DirListError dirlist_next_entry(handle h, DirEntry* result){
DIR* dirp = (DIR*)h;
dirent* dr;
if((dr = readdir(dirp)) == NULL){
return DIRLIST_END;
}
strcpy(result->entry, dr->d_name);
if(dr->d_type == DT_DIR){
result->is_directory = 1;
}
else if(dr->d_type == DT_REG){
result->is_directory = 0;
struct stat* buf;
stat(result->entry, buf);
result->size = buf->st_size;
}
return DIRLIST_OK;
}
Direntry.h 只是一个带有几个声明的标题:
#ifndef DIRENTRY_H
#define DIRENTRY_H
const int MAX_PATH_LENGTH = 1024;
typedef void* handle;
struct DirEntry{
char entry[MAX_PATH_LENGTH + 1];
int is_directory;
long long size;
};
enum DirListError{
DIRLIST_OK,
DIRECTORY_NOT_FOUND,
INCORRECT_DIRECTORY_NAME,
DIRLIST_END,
};
handle dirlist_start_find(const char* dir, DirListError* error);
DirListError dirlist_next_entry(handle h, DirEntry* result);
void dirlist_end_find(handle h);
#endif
【问题讨论】:
-
那是什么图书馆。我隐约记得以前看过它,但我需要一点记忆在那里慢跑。提及您正在使用的东西(标准库之外)总是一个好主意
-
您要读取什么文件系统? ... ntfs 有几个陷阱?捷径?怪事?这样我就因为几个问题提前放弃了目录树。我也不认识你正在使用的库。我在 linux 上使用了
。 -
您只对 8 种 d-types 中的 2 种采取了一些最小的操作...我建议您至少应该就检测到任何其他 d-types 发出警告,这可能是一个线索在那里。
标签: c++ c unix segmentation-fault