How to copy the front of a line to a separator

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]); /*Scan a string for the last occurrence of a character.*/ char *p = strrchr(szPath, '\\'); if (p) { *(p + 1) = 0; /* retain backslash and null terminate after that */ } else { /* handle error */ } printf("%s\n", szPath); 
+4
source share
1 answer

I would go with strrchr . This assumes str points to writable memory:

 char *p; if ((p = strrchr(str, '\\')) *(p + 1) = 0; /* Since we passed it to strrchr, it 0-terminated. */ 

Obviously, basename and dirname might be there if you work with paths and might be more appropriate.

+7
source

All Articles