我是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