Extract file name from full path in C using MSVS2005

In program C, I have the path to the file in the line (in particular, this is the name exestored in argv[0]). I would like to extract the file name and drop the directory path using MS Visual Studio 2005. Any built-in function for this?

+3
source share
4 answers

For reference, here is the code that I implemented is supposedly compatible with Win / Unix:

    char *pfile;
    pfile = argv[0] + strlen(argv[0]);
    for (; pfile > argv[0]; pfile--)
    {
        if ((*pfile == '\\') || (*pfile == '/'))
        {
            pfile++;
            break;
        }
    }
+3
source

Not really, just find the last backslash along the way. All after that is the file name. If nothing happens after this, the path indicates the 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;
}
+4
source

libc:

#include <unistd.h>

char * basename (const char *fname);
+2
source

This is the version of poorman:

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 _TCHARuse , and _tcschr strchr

strchrsimilar to: while((*p) && (*p != '\\')) p++; returning NULL to a safe place if chrnot found. Therefore, if you really do not 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
...

The smaller, the better use asm.

+1
source

All Articles