我是C++的新手,我有C#,Objective-C和JavaScript的经验。函数返回数组C++
此刻,我试图编写一个函数,它接受一个路径并返回一个目录列表(该路径中的所有文件和文件夹)。我在Ubuntu上做这个。
这里是我到目前为止的代码,说实话,我努力理解双指针语法以及它的实现,但是这是我的谷歌搜索导致我...
int FileManager::GetDirectoryListing(char *path, dirent **directoryEntries)
{
// Debug output...
printf("Listing directory at %s\n", path);
// Allocate memory for the directory entries
*directoryEntries = new dirent[MAX_FILES];
// Open the path we were provided
DIR *directory = opendir(path);
// A counter of how many entries we have read
int entryCount = 0;
// Make sure we were able to open the directory
if(directory) {
printf("Successfully opened directory\n");
// Read the first entry in the directory
struct dirent *directoryEntry = readdir(directory);
// While we have a directory entry
while(directoryEntry) {
// Debug output...
printf("%s\n", directoryEntry->d_name);
// Copy the directory entry to the array of directory entries we will return
memcpy(&directoryEntries[entryCount], directoryEntry, sizeof(struct dirent));
// Increase our counter
++entryCount;
// Read the next directory
directoryEntry = readdir(directory);
}
// Close the directory
closedir(directory);
}
return entryCount;
}
然后我打电话该功能通过:
dirent *directoryEntries = NULL;
int numberOfEntries = FileManager::GetDirectoryListing(deviceRootPath, &directoryEntries);
printf("File Manager returned directory listing.\n");
for(int i = 0; i < numberOfEntries; ++i) {
printf("Looping through directory entries, at index: %i\n", i);
printf("%s\n", directoryEntries[i].d_name);
}
它锁起来,当它试图访问的第一个元素在directoryEntries
即围绕循环中的第一次。
我知道我不理解双指针在干什么,我在GetDirectoryListing
的调用之后我的脑海里还没有清晰的图片说明directoryEntries
的结构。
发生了什么以及通过directoryEntries
循环的正确方法是什么?
+1:std :: vector比手动管理的数组更容易使用。 – dreamlax
@Jon:即使我几乎立即删除了这些行。 – Nawaz
在C++ 11中,如果元素个数不变,你也可以使用'std :: array'。 –
2011-09-10 15:41:12