Alphabetize text file?

I'm trying to make alphabetized lists of the items in given directories. From reading around I gather that when we read the contents of a directory, there's no simple way to read them in order? Is there a simple way to alphabetize the contents of a file after the fact? I'm assuming I need to read the contents into a vector and then order the vector but some of these files can be quite long with towards 1000 lines depicting as many items in the directory so that seems like a lot for a vector...
Please excuse my style, I prefer to write simple functions so it's easier to re-use them in other projects.
Below I'm checking to see if an earlier version of the temp file exists, deleting it if it's there, reading the directory contents and appending the contents to a new file.
I'd prefer to just read the directory in order if there's a trick for that in Linux.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
bool FileExists(string findFile){
	bool var0;
	FILE *file;
	if (file = fopen(findFile.c_str(), "r")) {
		fclose(file);
		var0 = 1;
   } 
return var0;
}
/////
void AppendString(string theFile, string words){
 	MyFile.open (theFile, ios_base::app);
	MyFile << words << endl;
	MyFile.close();
}
/////
void FilesToText(string dir){
	if(FileExists("temp.txt") == 1){
		remove("temp.txt");
	}
	string file;
	for(const auto & entry : filesystem::directory_iterator(dir)){
		file = entry.path();
			AppendString("temp.txt", file);
	}
}
Last edited on
This works, but it seems like workingVec could get REALLY BIG, lol. Note this version can be used to peruse recursively or the working directory only by commenting the unwanted part.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
void FilesToOrderedText(string dir){
	vector<string> workingVec;
	if(FileExists("temp.txt") == 1){
		remove("temp.txt");
	}
	string file;
//	for(const auto & entry : filesystem::directory_iterator(dir)){
//		file = entry.path();
//			workingVec.push_back(file);
//	}
	for(const auto & entry : filesystem::recursive_directory_iterator(dir)){
		file = entry.path();
			workingVec.push_back(file);

	}
    sort(workingVec.begin(), workingVec.end()); // Alphabetize

	for(auto i : workingVec){
		cout << i << " " << endl;
		AppendString("temp.txt", i);
	}

}
I don't think I understand your concern. If you have 1000 paths and each path is 100 characters long then it would only use around 100 KB. If you use directory_iterator to iterate over the files in a single directory (not recursive_directory_iterator) then you only need to store the filenames (not the whole paths) in the vector.
Last edited on
Registered users can post here. Sign in or register to post.