I need to grab the first part of the line to the last backslash in the path. I am new to C. So I was wondering if the following code is suitable? Or is there a better way?
#include <stdio.h> #include <string.h> int main(int argc, char* argv[]) { char szPath[260] = {0}; strcpy(szPath, argv[0]); char* p = szPath; size_t len = strlen(argv[0]); p+=len; //go to end of string int backpos = 0; while(*--p != '\\') ++backpos; szPath[len-backpos] = 0; printf("%s\n", szPath); return 0; }
After receiving comments changed to this:
char szPath[260]; strcpy(szPath, argv[0]); char *p = strrchr(szPath, '\\'); if (p) { *(p + 1) = 0; } else { } printf("%s\n", szPath);
source share