How to get the directory of a file from the full path in C

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));

Tags:

C

String

File

Path