I'm trying to dynamically obtain the parent directory (let's say C:\some\dir
) from a file name I get in an argument (say C:\some\dir\file
), and put it in a char*
. I already have the full path and file in a char*
. How exactly would I do that in C?
I have some code but in my mind it's all garbled and I can't make any sense of it. How should I rework/rewrite this?
/* Gets parent directory of file being compiled */
short SlashesAmount;
short NamePosition;
short NameLength;
char* Pieces[SlashesAmount];
char* SplitPath;
short ByteNumber;
short PieceNumber;
char* ScriptDir;
NameLength = strlen(File);
//Dirty work
SplitPath = strtok(File, "\");
do {
ByteNumber = 0;
do {
File[NamePosition] = CurrentPiece[ByteNumber];
NamePosition++;
} while(File[NamePosition] != '\n');
PieceNumber++;
} while(NamePosition < NameLength);
Click the Start button and then click Computer, click to open the location of the desired file, hold down the Shift key and right-click the file. Copy As Path: Click this option to paste the full file path into a document. Properties: Click this option to immediately view the full file path (location).
The full path name is the path from the root directory (i.e., / ). ./my_script is the relative path name, because the path is given relatively to the current directory, which is denoted by . . So if you are in your home directory the full path is s.th.
An absolute path always contains the root element and the complete directory list required to locate the file. For example, /home/sally/statusReport is an absolute path. All of the information needed to locate the file is contained in the path string.
Using the Combination of basename and dirname Commands Firstly, we use the dirname command to find the directory in which a file is located. Then we change the directory using the cd command. Next, we print the current working directory using the pwd command.
What you're looking for is dirname(3)
. This is POSIX-only.
A Windows alternative would be _splitpath_s
.
errno_t _splitpath_s(
const char * path,
char * drive,
size_t driveNumberOfElements,
char * dir,
size_t dirNumberOfElements,
char * fname,
size_t nameNumberOfElements,
char * ext,
size_t extNumberOfElements
);
Sample code (untested):
#include <stdlib.h>
const char* path = "C:\\some\\dir\\file";
char dir[256];
_splitpath_s(path,
NULL, 0, // Don't need drive
dir, sizeof(dir), // Just the directory
NULL, 0, // Don't need filename
NULL, 0);
You already have the full path of the file (for example: C:\some\dir\file.txt), just:
1. find the last slash by strrchr() : called p
2. copy from the beginning of the path to the p - 1 (do not include '/')
So the code will look like:
char *lastSlash = NULL;
char *parent = NULL;
lastSlash = strrchr(File, '\\'); // you need escape character
parent = strndup(File, strlen(File) - (lastSlash - 1));
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