Array loop not working
I've tried this:
if (argc > 2) {
int i;
for(i = 0; i < argc; i+开发者_C百科+) {
if(i != 0) {
rename_file(argv[i]);
}
}
}
if I pass in two file names only the first is renamed, whats wrong with this loop?
EDIT: Heres the rename_file function (it should work I think)
void rename_file(char const *filename) {
struct tm *clock;
struct stat attrib;
const char *dot = strrchr(filename, '.');
const char *ext = NULL;
if (dot && *dot) {
ext = dot + 1;
}
stat(filename, &attrib);
clock = gmtime(&(attrib.st_mtime));
char newname[250];
if (!ext) {
printf("ERROR: No File Extenstion");
} else {
sprintf(newname, "%02d_%02d_%02d.%s", clock->tm_mday, clock->tm_mon, clock->tm_year + 1900, ext);
}
rename(filename, newname);
}
Try this:
if (argc > 2) {
for(int i = 1; i < argc; i++) {
rename_file(argv[i]);
}
}
I don't see a bug as such, but I do see a lot of redundancy in the code. You could just do this:
for (i = 1; i < argc; i++)
{
rename_file(argv[i]);
}
If you don't have a debugger then you could add some debug printf
s temporarily:
printf("argc = %d\n", argc);
for (i = 1; i < argc; i++)
{
printf("i = %d, argv[i] = %s\n", i, argv[i]);
rename_file(argv[i]);
}
This will let you see what's going on in the loop prior to each call to rename_file
.
You're not checking the return value of rename
. If you pass the name of two files created on the same date (and with same extension), the second will likely fail (this is depending on your c lib though). And, fix your loop as everyone else pointed out.
If your command line looks like this:
./renamestuff stuff.txt stuff.php
Then you probably want this:
for(int i = 1; i < argc; i++) {
rename_file(argv[i]);
}
The first element argv[0]
contains the name of the executable itself. Therefore your loop should start with the first element.
精彩评论