0

I have a function inside my program to count the number of the files in a given directory. The function takes the input parameters as the name of the directory and the extension of the filename (type of files which have to counted in the directory).

I want to make it generic so that the caller of the function can specify any number of file extensions which can be taken as the input parameters and then the specific files having those extensions are counted.

void getNames(string dirName,  string fileExtension1, string fileExtension2, string fileExtension3){

vector<string> fileNames = //do some operations

if(fileType == fileExtension1 || fileType==fileExtension2....){
//increase count
}

return fileNames;
}

How do I change this function so that it takes any number of parameters and then the uses the same parameters inside the function to calculate the number of files?

user1240679
  • 6,829
  • 17
  • 60
  • 89

2 Answers2

7

Neatest way is to pass in a vector of extensions

void getNames(string dirName, const vector<string>& fileExtensions)

Now your if will be inside a for loop

for(int i = 0; i<fileExtensions.size();i++){

    if(fileType == fileExtension[i]){
        //increase count
        break;// this might be needed to ensure no multiple positives? depending on what you want to do.
    }

}
Karthik T
  • 31,456
  • 5
  • 68
  • 87
0

In your code, you have type based decisions:

if(fileType == fileExtension1 || fileType==fileExtension2....){
//increase count
}

return fileNames;
}

If you will have a lot of fileTypes and functions operating on them, each time you will need some fileType specific operation, you will end up with extensive type based decision logic (if you are this type, do that, else if you are ...).

Since the function is doing something to a "fileName" based on a "fileType" (extension), you might consider encapsulating both into a class File, because each file has a name and extension. Your function will then be operating on a set of File objects. If the set of file objects is something you are working on in many places, you can define a class e.g. FileSet which can then be implemented with a vector, list, or whatever container to store the files. This way you will end up with a function taking a single argument e.g. const FileSet&, and the rest of the code will be dealt with by the File class. Anyway, this is not a definiteve answer, I only suggest to think about the OOdesign of your code.

tmaric
  • 5,347
  • 4
  • 42
  • 75