我想用下劃線替換空格字符並重命名目錄中的文件名。一切看起來不錯,但重命名操作不重命名文件。重命名文件名C++
DIR *dir;
char *directoryPath = "E:\\markdown-here.wiki\\LeetCode_problems_solution\\";
struct dirent *ent;
if ((dir = opendir (directoryPath)) != NULL) {
while ((ent = readdir (dir)) != NULL) {
char *filename;
for(int i = 0; i < strlen(ent->d_name); ++i) {
if(ent->d_name[i] == ' ')
filename[i] = '_';
else filename[i] = ent->d_name[i];
}
filename[strlen(ent->d_name)] = '\0';
// output: Error renaming file: No such file or directory
int result = rename(ent->d_name, filename);
if(result == 0) puts ("File successfully renamed");
else perror("Error renaming file");
// this works
printf ("%s, %s\n", ent->d_name, filename); // foo bar, foo_bar
}
closedir (dir);
} else {
/* could not open directory */
perror ("");
return EXIT_FAILURE;
}
這裏有什麼問題?
你從'perror'得到什麼信息? – 2014-10-01 22:23:08
重命名文件時出錯:沒有這樣的文件或目錄 – 2014-10-01 22:23:23
變量filename沒有初始化,甚至沒有初始化 – kotlomoy 2014-10-01 22:24:09