I'm really new to C and all I know is that the error is related to oldname
and newname
not be initialized
#include <stdio.h>
int main (int argc, char const *argv[])
{
int result;
int lengthOne;
int lengthTwo;
lengthOne = sizeof(argv[0]);
lengthTwo= sizeof(argv[1]);
char oldname[lengthOne] = argv[0];
char newname[lengthOne] = argv[1];
result = rename(oldname, newname);
if (result == 0) {
puts "File renamed";
} else {
perror "ERROR: Could not rename file";
}
return 0;
}
app.c: In function ‘main’:
app.c:11: error: variable-sized object may not be initialized
app.c:12: error: variable-sized object may not be initialized
app.c:17: error: expected ‘;’ before string constant
app.c:19: error: expected ‘;’ before string constant
lengthOne = sizeof(argv[0]);
lengthTwo= sizeof(argv[1]);
This gives you the size of a char*
, not the length of the string. You meant strlen
, not sizeof
.
char oldname[lengthOne] = argv[0];
char newname[lengthOne] = argv[1];
You can't assign to arrays like that. You could strcpy
them, but it's unnecessary here because you can just use pointers.
const char* oldname = argv[0];
const char* newname = argv[1]; // But verify that argc >= 2 first!
EDIT: Also, don't forget that argv[0]
is the name of the program itself, and argv[1]
is the first argument. If your intent was to write a mv
-like program instead of a program that renames itself, you want argv[1]
and argv[2]
.