Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parent directory of a file

Tags:

c

Is there any way to find out the parent directory of a file using C program. I would like to give same permissions for the file that the directory has. So as to do so, i would like to know the parent directory of the file. Any help is appreciated.

like image 799
nikhil Avatar asked Mar 22 '11 14:03

nikhil


People also ask

What is the parent directory of a file?

2. With a directory, a parent directory is a directory containing the current directory. For example, in the MS-DOS path below, the "Windows" directory is the parent directory of the "System32" directory, and C:\ is the root directory.

How do I get the parent directory of a file?

Use File 's getParentFile() method and String. lastIndexOf() to retrieve just the immediate parent directory. There are several variants to retain/drop the prefix and trailing separator. You can either use the same FilenameUtils class to grab the name from the result, use lastIndexOf , etc.

Where is the parent folder?

In the Properties window, select the "Location" tab. The file path will be listed under "Target." The parent folder will be the folder that is listed before the final slash in the file path. For example, if the file path is "C:\Users\username\Documents\myfile.

Which command is used in parent directory?

cd .. : this command is used to move to the parent directory of current directory, or the directory one level up from the current directory.


2 Answers

If you have the path of the file, you can do it manually by making it an absolute path if it is relative (doesn't begin with a / on Unix, or a letter:\ or \ or letter:/ or / on Windows) and then splitting it on file separator characters (/ or \), but I am aware of no built-in function that will do all of this for you.

The basename and dirname functions may help, but you'll need to figure out enough of the path of the file yourself, as they only work with strings; they do not interrogate the file system.

like image 107
Jonathan Avatar answered Sep 28 '22 07:09

Jonathan


It's not guaranteed to do The Right Thing, but have you tried any of the following:

  • If your filename contains a path separator (e.g. / on Unix, \ on Windows), copy the string using e.g. strdup() and replace the last occurence of the path separator (found with e.g. strrchr()) with a zero/null character. The resulting string will be the parent directory of your file.

  • If there is no path separator, then the file resides within your current working directory. Have you tried just using .? The . and .. links work on both Unix and Windows.

There are quite a few corner cases above (e.g. what of the file /hello.txt?), but it should be a start.

like image 44
thkala Avatar answered Sep 28 '22 08:09

thkala