Can any one please tell me how to implement GetFileName() function in C without using string inbuilt function of C. For example C:\Program Files\hello.txt
output : hello.txt
Can any one please tell me how to implement GetFileName() function in C without using string inbuilt function of C. For example C:\Program Files\hello.txt
output : hello.txt
Loop through the string looking for the last separator. If /
, \
and :
are valid path separators (Windows):
char *getFileName(char *path) {
char *retVal = path, p;
for (p = path; *p; p++) {
if (*p == '/' || *p == '\\' || *p == ':') {
retVal = p;
}
}
return retVal;
}
Without using built-in string functions, I assume you can't use strlen
or strdup
. The simplest way you can achieve that is:
char *fname(char *path)
{
char *aux = path;
/* Go to end of string, so you don't need strlen */
while (*path++) ;
/* Find the last occurence of \ */
while (*path-- != '\\' && path != aux) ;
/* It must ignore the \ */
return (aux == path) ? path : path + 2;
}
path
had no occurrence of \\
.Starting at the end of the path you can copy characters from the path to another string until you find the '\' character. So after the while loop the reverseFileName
string will be 'txt.olleH'
. The for loop reverses the 'txt.olleH'
to 'Hello.txt'
char* GetFileName(char[] path)
{
char *reverseFileName = malloc(100*sizeof(char));
int len = strlen(path);
int i=len-1;
int j=0;
while( (path[i] != '\') && (i>=0) )
{
reverseFileName[j] = fileName[i];
i--;
j++;
}
reverseFileName[j+1]='\0';
int reverseLength = strlen(reverseFileName)
char *fileName = malloc( (reverseLength+1)*sizeof(char) );
j=0;
for(i=reverseLength-1; i>=0; i++)
{
fileName[j] = reverseFileName[i];
j++;
}
free(reverseFileName);
return fileName;
}