I am using and understanding strtok for a while but this time it is giving unexpected error. I can't figure out what's wrong. Please help. I am using Visual Studio on Windows 10.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char* argv[])
{
char* filepath = "C:\\Users\\RAKESH\\source\\repos\\TESTING\\log.c";
char* filename = strtok(filepath, "\\");
while (filename != NULL)
{
filename = strtok(NULL, "\\");
}
printf("%s\n", filename);
return 0;
}
Before I posted this question, I found the error intuitively. Actually strtok needs to manipulate the char array, so it needs read-write memory space in the char array to do so, so it can't work with string literals which are typically stored in read-only memory. So the solution is:
Note: This code does not give the filename but returns NULL as the filename, so to get the actual filename, the following code changes in the while loop are required: