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.
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.
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.
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.
cd .. : this command is used to move to the parent directory of current directory, or the directory one level up from the current directory.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With