Extract file name from full path in C using MSVS2005

前端 未结 5 843
执念已碎
执念已碎 2020-12-10 21:07

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

相关标签:
5条回答
  • 2020-12-10 21:22

    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;
            }
        }
    
    0 讨论(0)
  • 2020-12-10 21:30

    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..

    0 讨论(0)
  • 2020-12-10 21:33

    If you wanted a function from libc:

    #include <unistd.h>
    
    char * basename (const char *fname);
    
    0 讨论(0)
  • 2020-12-10 21:35

    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;
    }
    
    0 讨论(0)
  • 2020-12-10 21:37

    Use _splitpath(). See https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/splitpath-wsplitpath?redirectedfrom=MSDN&view=vs-2019 for details

    0 讨论(0)
提交回复
热议问题