Hi all, I've done this prog to get the last token in a string
es: /dir1/dir2/file.txt must return --> file.txt

I get several errors on assignments, what's wrong with it?
many thanks

int main()  {
char *path;
char *filename;

path = (char*) malloc(sizeof(char) * 64);
strcpy(path, "/dir1/dir2/file.txt");

filename = get_filename(path);

printf("%s\n", filename);
    return 0;
}


char* get_filename(char *path)  {
char* filename;
filename = // calculate filename with strtok(), it works ok (printf checked)
return filename;
}

Recommended Answers

All 5 Replies

try this function:

One way is to

char * get_filename(char *path) {
char filename[30];
int len = strlen(path);
char *fromLast = path + (len -1);
int i = 0;
while(*fromLast != '/') {
fromLast --;
}
strcpy(filename, fromLast);

return filename;

}

Hi Luckychap, first of all thanks for your reply.
My problem is not in the function working on the string, that works well, but in main(): I cannot do assignment
filename = get_filename(path);
that seems to me quite strange since filename is declared as char* and my function get_filename(char *path) is declared to return a char*.
I want to pass a string to a function, let the function do something on it and return the modified string to the caller which would assign it to a char* different variable;
surely there're some big holes in my char* management abilities.....

its not necessary to use strtok() to get the filename part. Just call strrchr(). This is a safer way to do it because strtok() requires non-literal strings and the function below doesn't.

char* get_filename(char *path)  {
    char* ptr = strrchr(path,'/');
    if( ptr != NULL)
        ptr++;
    return ptr;
}

>>that seems to me quite strange since filename is declared as char* and my function
>> get_filename(char *path) is declared to return a char*.

Unless you want to do something that you did not post then what you posted should work ok. You can also call that function like this -- assuming it doesn't use strtok() filename = get_filename("/dir1/dir2/file.txt");

in place of "filename = get_filename(path)"
use strcpy(filename, get_filename)

Ok, with strrchr() and strcpy() it finally worked! :icon_wink:

Anway, in case I need to modify the original string, in K&R I read to pass a pointer to it, where am I wrong? I don't know where to allocate filename buffer

int main()  {
    
    char *filename;

    //here or in get_filename? or both?
    filename = (char*) malloc(16 * sizeof(char)); 

    get_filename( &filename );

    printf("%s", *filename);

    return 0;
}


void get_filename( char **filename )  {
    
    //write in filename, need a realloc?
    strcat(*filename, something);    

}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.