How to copy files from unknown folder?

I'm trying to formulate a way how can I copy file to root directory from the unknown one (unknown means that I don't know its name). For example, I want to copy d:\tea\unknown\black.txt to d:\tea\black.txt. I found that it's possible in Cmd: copy files into unknown directory

How can it be done in C++?
What would make sense is to go through all folders within "Tea" and then search them all for "black.txt", error handling for the inevitability that you'll run into many folders before finding it.

For this, you'd want to make a list of all directories/folders within "tea"

https://stackoverflow.com/questions/5043403/listing-only-folders-in-directory
I got some working code:

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
std::vector<std::string> get_directories(const std::string& s)
{
	std::vector<std::string> r;
	for (const auto & entry : std::filesystem::directory_iterator(s))
	{
	//	std::cout << entry.path() << std::endl;
		r.push_back(entry.path().string());
	}

	return r;
}

int main() 
{
	std::string s = "C:\\Users\\Lelouch";

	std::vector<std::string> r = get_directories(s);

	for (int i = 0; i < r.size(); i++)
	{
		std::cout << r[i] << '\n';
	} 

	return 0;
}


The vector "r" will contain all the folders in the directory. So from there, you can use the stream to go through them, opening them up and checking for "black.txt" until you find it.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <memory>
#include <filesystem>
#include <algorithm>
#include <iostream>

namespace fs = std::filesystem;

int main() try
{
    std::for_each(fs::recursive_directory_iterator("./foo/"), {},
                  [](fs::directory_entry const& dirent) 
                  {
                    if (fs::is_regular_file(dirent) && 
                        dirent.path().filename() == "black.txt")
                      fs::copy(dirent, "./foo/");
                  });
} 
catch (fs::filesystem_error const& e) 
{
    std::cerr << "error: " << e.what() << '\n';
}

Live demo:
http://coliru.stacked-crooked.com/a/4e3be7a2eb060148
Last edited on
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
27
28
29
30
#include <iostream>
#include <vector>
#include <filesystem>
#include <string>
#include <fstream>


int main() 
{
	std::string s = "C:\\Users\\Lelouch";

	std::vector<std::string> r;
	for (const auto & entry : std::filesystem::directory_iterator(s))
	{
		r.push_back(entry.path().string());
	}

	for (int i = 0; i < r.size(); i++)
	{
		r[i].append("\\black.txt");

		std::ifstream inFile;
		inFile.open(r[i]);
		if (inFile.is_open())
		{
			std::cout << "We Found It! In the Directory: " << r[i] << '\n';
			break;
		}
	}
}
Last edited on
Thanks, both work, do you maybe know how r[i] or dirent can be converted to tchar?
Why on earth would you want to do that!?
I want to use variable somewhere else
Topic archived. No new replies allowed.