I am trying to write a function which would return the file name of a file, from its file address. It simply copies each character of the address, starting from the termination charater, uptil the first forward-slash '\\'
, to a char array variable named name
. And then, it simply reverses the order of all the charater in the variable name
. I wrote a function called file_name()
, like this:
char* file_name(char* addr){
static char name[100];
char temp;
int i = -1;
for (; addr[i] != '\\'; --i){
name[-1-i] = addr[i]; // -1-i increases from 0 as i decreases. We get the reversed name of the file in "name"
}
int len = -i; //array length is simply -i. we know that through as i acts as the counter in the above iteration.
for (int count = 0; count < len; ++count){
temp = name[count];
name[count] = name[len - 1 - count];
name[len - 1 - count] = temp;
}
return name;
}
I have declared name
as a static variable, after receiving a warning from the compiler, and looking it up on Google. I found that without declaring it with the static
keyword(or through dynamic allocation), name
is treated as a local variable, and being an array, gets 'deleted' after the return statement(I would like to know a proper explanation. I still kinda don't understand what that is. Only have a vague idea).
Now, this compiles just fine, after adding the main
function to the code:
int main(int argc, char** argv){
char* name = file_name(argv[1]);
printf("File name is: %s", name);
return 0;
}
Now, for some reason, I get no output. I give the executable a parameter with a valid file address, but it gives no output. On top of that, it just stalls for a few seconds, and exits. What's going on? I don't think it's a problem with the algorithm. The function has no problem returning arrays, as it works well in a simpler case. Why is it not working?
I am working on Windows 10 with the GNU compiler collection.
P.S. - I would be grateful to know if there is already a function in the standard library which returns file name from address. But nonetheless, would still want to know why my code isn't working.