filesystem::current_path

With maneuvering the filesystem relative to the working directory to enter various sub-directories I've been using a string:

1
2
    filesystem::current_path("SubDirName"); // from parent to sub
    filesystem::current_path("/ParentDirName"); // back up from sub to parent 


I'd like to do this with a string variable rather than have an ocean of logical code like this:

1
2
3
4
5
string parent, sub;
parent = "/ParentDirName";
sub = "SubDirName";
    filesystem::current_path(sub); // from parent to sub
    filesystem::current_path(parent); // back up from sub to parent 


But it doesn't work... ugh.
Is there a way to do this with std::filesystem?

Thanks for taking the time to read, Tom
Linux with gcc version 7.5.0
Last edited on
To navigate, use std::filesystem::path.
To get the std::string from the path: https://en.cppreference.com/w/cpp/filesystem/path/string

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <filesystem>

int main()
{
    namespace fs = std::filesystem ;
    const fs::path parent_path = "/var/tmp/l67gs" ;
    const fs::path sub_dir = "tmp_dir" ;

    fs::path curr_path = parent_path / sub_dir ; // from parent to sub
    std::cout << curr_path << '\n'
              << "parent: " << curr_path.parent_path() << '\n'; // / back up from sub to parent 
}

http://coliru.stacked-crooked.com/a/2b0fadbcd756b247
Apologies JLBorges,
I didn't see your response until now, I'll try this today, thank you for the help!
Is there a way to do something like this so the complete path doesn't need to be specified?
1
2
	auto path = filesystem::current_path();
	const filesystem::path parent_path = current_path;
I got it!!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

#include <iostream>
#include <filesystem> 
using namespace std; 

int main()
{

	auto path = filesystem::current_path();
        cout << "in working directory" << endl;

	filesystem::current_path(subdir);  // to subdirectory
        cout << "in subdirectory" << endl;

	filesystem::current_path(path); // back to parent directory stored as "path"
        cout << "back in working directory" << endl;

}


I guess I just failed to comprehend that "path" was a usable string variable
Last edited on
compile string for future noobs like me learning to use std::filesystem ---- ymmv depending on your gcc version

1
2
3

g++-8 -std=c++17 ProgramName.cpp -lstdc++fs
Last edited on
Topic archived. No new replies allowed.