Organizational Research By

Surprising Reserch Topic

get file name from a path string implementation in c


get file name from a path string implementation in c  using -'c'

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
    

asked Sep 9, 2015 by ColeNollektb
0 votes
5 views



Related Hot Questions

3 Answers

0 votes

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;
 }
answered Sep 9, 2015 by GabrielParri
0 votes

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;
}
answered Sep 9, 2015 by KristiWeathe
0 votes

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)
{
    /* Go to end of string, so you don't need strlen */
    while (*path++) ;

    /* Find the last occurence of \ */
    while (*path-- != '\\') ;

    /* It must ignore the \ */
    return (path + 2);
}
answered Sep 9, 2015 by BretMedeiros

...