Remove text from string after a certain repeated character

Viewed 57
char str[] = "C:\\Users\\test\\Desktop\\folder\\test.txt";
char *ptr;

ptr = strchr(str, '\\');
if (ptr != NULL) {
    *ptr = '\0';
}

How do I remove the last ' \ ' including test.txt so it is just "C:\Users\test\Desktop\folder"

Thanks

1 Answers

You want strrchr

Locate last occurrence of character in string Returns a pointer to the last occurrence of character in the C string str.

The terminating null-character is considered part of the C string. Therefore, it can also be located to retrieve a pointer to the end of a string.

Also you need to escape the backslashes with \\:

#include <stdio.h>
#include <string.h>
 
int main(void)
{
    char str[] = "C:\\Users\\test\\Desktop\\folder\\test.txt";
    char *ptr;

    ptr = strrchr(str, '\\');
    if (ptr != NULL) {
        *ptr = '\0';
    }
    puts(str);
}
Related