You cannot append ".dat"
directly to argv[i]
because argv[i]
has a allocated size that can only hold its original content.
To understand what is happening, imagine argv
is something like this:
char buffer[] = "./test\0paul\0tony\0john\0";
char *argv[4] = { &buffer[0], &buffer[7], &buffer[12], &buffer[17] };
So as you can see, if you write something after "paul"
you will overwrite "tony"
and break the whole thing because they are serialized in the same buffer.
To workaround this, you have to copy each argv[i]
to a bigger buffer where you can safely make the modifications. For instance:
int i;
char filename[1024];
for (i = 1; i < argc; ++i) {
sprintf(filename, "%s.dat", argv[i]);
// ... do stuff
}
Then you will have a variable filename
containing the desired filename without corrupting argv
.