In a C program, I have a file path in a string (specifically, this is the exe
name stored in argv[0]
). I would like to extract the file name and di
For reference, here's the code I implemented, supposedly Win/Unix compatible:
char *pfile;
pfile = argv[0] + strlen(argv[0]);
for (; pfile > argv[0]; pfile--)
{
if ((*pfile == '\\') || (*pfile == '/'))
{
pfile++;
break;
}
}
This is the poorman's version:
char *p, *s = args[0]; // or any source pathname
...
p = strchr(s, '\\'); // find the 1st occurence of '\\' or '/'
// if found repeat the process (if not, s already has the string)
while(p) {
s = ++p; // shift forward s first, right after '\\' or '/'
p = strchr(p, '\\'); // let p do the search again
}
// s now point to filename.ext
...
note: for _TCHAR
, use _tcschr
rather that strchr
strchr
is similar to: while((*p) && (*p != '\\')) p++;
with safebelt NULL return if chr
is not found.
So if you really don't like to depend on another lib you can use this:
char *p, *s = args[0];
...
p = s; // assign to s to p
while(*p && (*p != '\\')) p++;
while(*p) { // here we have to peek at char value
s = ++p;
while (*p && (*p != '\\')) p++;
}
// s now point to filename.ext
...
Any lower than that, use asm
instead..
If you wanted a function from libc:
#include <unistd.h>
char * basename (const char *fname);
Not really, just locate the last backslash in the path. Anything after that is the filename. If nothing is after that, the path specifies a directory name.
// Returns filename portion of the given path
// Returns empty string if path is directory
char *GetFileName(const char *path)
{
char *filename = strrchr(path, '\\');
if (filename == NULL)
filename = path;
else
filename++;
return filename;
}
Use _splitpath(). See https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/splitpath-wsplitpath?redirectedfrom=MSDN&view=vs-2019 for details