How to get the directory of a file from the full path in C
Solution 1
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);
Solution 2
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));
AlexTheRose
Sorry, but this section failed parsing procedures. Try reloading the page.
Updated on June 04, 2022Comments
-
AlexTheRose almost 2 years
I'm trying to dynamically obtain the parent directory (let's say
C:\some\dir
) from a file name I get in an argument (sayC:\some\dir\file
), and put it in achar*
. I already have the full path and file in achar*
. 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);