找到文件,但名称未更新

时间:2016-06-07 19:27:56

标签: c

我做了这段代码来检查给定的文件名是否为" .jpg"如果是,请将其更改为" .png":

#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <stdio.h>


char newname[2000];

customRename(char *name) {
    int i = strlen(name), 
    answer;

    memset(newname, '\0', sizeof(newname));
    strcpy(newname, name);

    if ((name[i-1] == 'g') && (name[i-2] == 'p') && (name[i-3] == 'j') && (name[i-4] == '.')) {
        newname[i-2] = 'n';
        newname[i-3] = 'p';
        answer = rename(name, newname);
        if (answer == -1) { 
            fprintf(stderr, "%s -> %s: %s\n", name, newname, strerror(errno)); 
        } else {
            printf("%i: ", answer);
            puts(newname);
        }
    }
}

void listdir(const char *name, int level)
{
    DIR *dir;
    struct dirent *entry;

    struct stat s;

    if (!(dir = opendir(name)))
        return;
    if (!(entry = readdir(dir)))
        return;

    do {
        if (S_ISDIR(s.st_mode)) {
            char path[1024];
            int len = snprintf(path, sizeof(path)-1, "%s/%s", name, entry->d_name);
            path[len] = 0;
            if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
                continue;
            }
            //printf("%*s[%s]\n", level*2, "", entry->d_name);
            listdir(path, level + 1);
        }
        else {
            //printf("%*s- %s\n", level*2, "", entry->d_name);
            customRename(entry->d_name);
        }
    } while (entry = readdir(dir));
    closedir(dir);
}




int main() {

    printf("Root path:\n");

    char rootpath[2000];
    gets(rootpath);
    listdir(rootpath, 0);

    return 0;
}

但是,由于某些未知原因,它打印出来:

-1: LF1603300450121ARG.png

-1意味着出了问题......但出了什么问题?

提前致谢。

1 个答案:

答案 0 :(得分:0)

int n = strlen(name);
if ( n > 4 ) {
   if ( strcmp(&name[n-4], ".jpg") == 0 ) {
      strcpy( &name[n-3], "png";
   }
}