At least that is what I think I want to do.
What is the proper way for me to return multiple data member objects
from an accessor method in my class while ensuring the data does not
get changed, but allowing iteration through the data?
I tryed returning a const vector but the compiler does not like the
idea of my using an iterator to look through the vector down the
road...I assume because an iterator acts like a pointer and allows you
to change the data?
Thanks,
Christopher
Here is my class currently:
#include <direct.h>
#include <winsock2.h>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
//------------------------------------------
class Directory
{
public:
Directory(){}
~Directory(){}
// Accessors
string & GetPath()
{
return m_path;
}
vector<Directory> & GetSubdirectories()
{
return m_subdirectories;
}
vector<string> & GetFilenames()
{
return m_filenames;
}
// Mutators
//--------------------------------
// Gather file and subdirectory info from the directory specified by
path
// Note: (recursive)
bool Set(const char * path)
{
// Make sure the path points to a valid directory
HANDLE file_handle = INVALID_HANDLE_VALUE;
WIN32_FIND_DATA file_data;
DWORD error;
// Add the wild card character to the path to search it's
contents
string search_path(path);
search_path += "\\*";
// Search for the first file or directory in the path
file_handle = FindFirstFile(search_path.c_str(), &file_data);
// Was the supplied path a valid directory? (there would at least
be a "." or ".." found)
if(file_handle == INVALID_HANDLE_VALUE ||
!(file_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) )
{
cout << path << "\n is an invalid directory. Error:" <<
GetLastError() <<endl;
FindClose(file_handle);
return false;
}
else
{
// Set this directory object's path to the supplied path
m_path = path;
// Do the following until no more files or directories are
found
do
{
// Skip the . and .. directories
if( strcmp(file_data.cFileName,".") != 0 &&
strcmp(file_data.cFileName,"..") != 0 )
{
// Check if we found a file or a directory
if(file_data.dwFileAttributes &
FILE_ATTRIBUTE_DIRECTORY)
{
// Get the path to the subdirectory
Directory subdirectory;
string subdir_path(path);
subdir_path += "\\";
subdir_path += file_data.cFileName;
// Read the subdirectory's contents
subdirectory.Set(subdir_path.c_str());
// Insert the record
m_subdirectories.push_back(subdirectory);
}
// Otherwise, we found a file
else
{
// Get the filename
string filename(file_data.cFileName);
// Insert the record
m_filenames.push_back(filename);
}
}
}while(FindNextFile(file_handle, &file_data) != 0);
}
// Release the file handle
FindClose(file_handle);
return false;
}
private:
// Data
string m_path;
vector<Directory> m_subdirectories;
vector<string> m_filenames;
};