Re: split a /path/filename into components



On a sunny day (Sat, 26 Aug 2006 12:40:02 -0400) it happened kenneth kahn
<kenkahn@xxxxxxxxxxxxx> wrote in <DP_Hg.3539$k%3.1479@xxxxxxxxxxxx>:

Eric wrote:
Is there a C library function that can take a path and break it into its
component parts? I think dos has one called fnsplit but i cant seem to find
an equal in the linux world

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int ArgC,char *ArgV[]) {

char *Ptr;
char path[255],file[64];

Ptr = strrchr(ArgV[1],'/');
strcpy(path,(Ptr == NULL) ? "./" : (Ptr[0]='\0',ArgV[1]));
strcpy(file,(Ptr == NULL) ? ArgV[1] : Ptr+1);

printf("path=%s file=%s\n",path,file);

return 0;

}


path and file are limited... overflow may happen...


#include <stdio.h>
#include <stdlib.h>

#define _GNU_SOURCE
#include <string.h>

int main(int argc, char **argv)
{
char *ptr;
char *path;

ptr = strrchr(argv[1], '/');
if(! ptr)
{
fprintf(stderr, "file=%s in current directory\n", argv[1]);

return 0;
}

path = (char *)strndup(argv[1], ptr - argv[1]);
if(! path)
{
fprintf(stderr , "buy some memory, malloc failed, aborting.\n");

return 1;
}

fprintf(stderr, "path=%s file=%s\n", path, ptr + 1);

fprintf(stderr, "Whoopy, without arrays!\n");

return 0;
}


















.



Relevant Pages