kilpikonna
kilpikonna

Reputation: 137

C++ Path to the directory given its name

I'm writing a C++ program in Linux and I would need to change the current directory. I have a name of the directory I want to change it on, and I want to use the chdir(). But it's argument is a path (i.e. the char* containing the directory location). And I don't have the full path, but just the name of directory.

I've seen this question: Changing the current directory in Linux using C++

However, I think that the proposed solution works only if the new directory is the sub directory of the current directory - otherwise, it doesn't make a sense for me if there can be more different directories of the same name in my computer (please, tell me if I'm wrong).

I'm not sure if I'm clear, to be sure, here is the example:

-CurrentDirectory
    |
    - Subdirectory
    |
    - ... etc.
- AnotherDirectory 

In my opitnion, if I want change the current directory to Subsirectory, chdir(Subdirectory.c_str()) would work. But not chdir(AnotherDirectory.str()) (which has nothing in common with CurrentDirectory in general). I know this question has to be already answered somewhere, but I'm not able to find it.

Thank you for your time!

Upvotes: 1

Views: 135

Answers (3)

First, you might have several sub-directories (in various directories) sharing the same name (so you could have both a/xx/ and b/c/xx/)

You could use nftw(3) to find something in a file tree and getcwd(2) to get the current directory. You could also consider using opendir(3), readdir(3), closedir(3) to scan one directory (and build complete paths to be passed to stat(2))

Then, to get some "canonical" path, consider using realpath(3)

Notice that glob(3) (see also glob(7)), fnmatch(3), wordexp(3) could be useful too.

Upvotes: 0

John Zwinck
John Zwinck

Reputation: 249592

It seems like you want to "search" for a directory by name. I suggest using the locate database for this. You can try it on the command line:

locate AnotherDirectory

This will print all the files and directories on your local disks which are indexed.

Using this database could improve performance a lot if you don't know where to look for this directory. You can read about where to find the underlying file here: https://serverfault.com/questions/454127/where-is-the-updatedb-database-located - but you could also just use popen() to run the locate program for a more portable solution than directly reading the database files.

Of course you will still need to write application logic to deal with multiple directories having the same name and so on.

Upvotes: 0

lostbard
lostbard

Reputation: 5230

You could use getcwd to get the absolute path name of the current directory.

#include <unistd.h>

char * getcwd(char *buf, size_t bufsize);

To change to another directory, you need know either the absolute path to the other direrctory, or its relative path to it such as ../someotherdirectory

Upvotes: 2

Related Questions