I need to scan a directory and get the files located in it, which is not a problem, but I also need to know if the directory contains folders because I also need to open the folder and get the files in those directories. I put this code together and it gets me two levels deep in the directory but I know there has to be a better way to do this. I would basically have to keep repeating the if file does not end in .txt or .tsv over and over for however deep the directory listing so this definitely makes me think there is a better way to do this. Any help would be greatly appreciated. Here's the code I have:

void getFileList( DIR* dirp, dirent* entry, vector<string> &fileList, char* argv[] )
{
	string fileExtension = "";
	string directory = "";
	DIR* dir2;
	dirent* innerEntry;
	string slash = "/";

	if( dirp = opendir(argv[1]) )
	{

	    while( entry = readdir(dirp) )
	    {

	      	// Ignore dot and dotdot, if found jump back to loop start
	      	if ( (strcmp(entry->d_name, ".") == 0) || (strcmp(entry->d_name, "..") == 0) )
	        	continue;

	      	fileExtension = entry->d_name;
		directory = argv[1] + slash + entry->d_name;
		const char* d;
		d = directory.c_str();
		cout << "Directory is " << directory << endl;
		cout << d << endl;
	
	      	//remove non necessary parts of string, only leaving extension e.g. ".txt"
	      	for (string::iterator j = fileExtension.end() - 5; j >= fileExtension.begin(); --j)
	            	fileExtension.erase(j);

		cout << "File Extension is " << fileExtension << endl;

	      	//ignore non-txt and non-tsv files
	      	if( fileExtension != ".txt" && fileExtension != ".tsv")
		{
			if ( dir2 = opendir(d) )
			{
				while ( innerEntry = readdir(dir2) )
				{
					if ( (strcmp(innerEntry->d_name, ".") == 0) || (strcmp(innerEntry->d_name, "..") == 0) )
	        			continue;
					fileList.push_back(innerEntry->d_name);
				}
				closedir(dir2);
			}
		}
	        //continue;
		else
		{
	      		fileList.push_back(entry->d_name);  // Place filename onto back of vector
		}
	    }

	    closedir(dirp);                        // Close directory when no files remain
	}

	 //toss error if directory not found
	else
	{
		 cout << "Directory not found" << endl;
		 displayHelp();
		 exit (1);
	}
}

Recommended Answers

All 2 Replies

Why not just call getFileList() recursively if you have a directory?

Thank you Salem. I honestly don't know why I didn't think of that. Thanks. Now I just have to figure out how to open those files that are in a directory other than the root folder. Thanks again. I appreciate it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.