Parent file directory

Is there a way to find out the parent directory of a file using program C. I would like to provide the same permissions for a file that has a directory. To do this, I would like to know the parent directory of the file. Any help is appreciated.

+4
source share
3 answers

There is no such function in C. You can try your luck on Windows: GetFullPathName http://msdn.microsoft.com/en-us/library/aa364963%28v=vs.85%29.aspx

and then maybe _splitpath http://msdn.microsoft.com/en-us/library/e737s6tf%28v=vs.80%29.aspx

But, as it is written, there is no standard function for performing such things.

+2
source

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

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

+3
source

It is not guaranteed to do the β€œRight Thing”, but you have tried one of the following:

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

  • If the path separator is missing, the file is in your current working directory. You tried just using it . ? References and .. work on both Unix and Windows.

There are quite a few corner cases (for example, the file /hello.txt ?), But this should be the beginning.

+1
source

Source: https://habr.com/ru/post/1344778/


All Articles