I\'m really new to C and all I know is that the error is related to oldname
and newname
not be initialized
#include
in
sizeof is a compile-time check... the sizeof any argv element will be the number of bytes in a pointer-to-char. It has nothing to do with the run-time length of the text that pointer may address: strlen()
returns that. But, C doesn't let you create dynamically (i.e. runtime) sized arrays. And even then you can't copy a string into another string with =
... it requires a call to strcpy(dest, src)
. To make it work, obviously the easiest thing is:
result = rename(argv[0], argv[1])
But, I appreciate you're trying to learn how to copy the values into your own buffer. To do so, you need to dynamically create a sufficiently large buffer (memory-allocate or malloc
), string-copy it, use it then free
it. Several of these requirements are satisfied by the strdup()
function:
const char* p_old_name = strdup(argv[0]);
const char* p_new_name = strdup(argv[1]);
rename(p_old_name, p_new_name);
free(p_old_name);
free(p_new_name);
Alternatively, you can statically specify a maximum size for the two strings (dangerous if you get it wrong - strncpy() can provide a more safety but a mistake may still prevent your program working with some long-but-valid paths):
#include // or wherever you can find PATH_MAX or similar
...
char old_name[PATH_MAX];
char new_name[PATH_MAX];
strcpy(old_name, argv[0]);
strcpy(new_name, argv[1]);
rename(old_name, new_name);
Note: as argv[0]
is the program name, this program changes it's own executable name to whatever the second argument is. If you want it to change another file's name, then you should use argv[0]
and argv[1]
.