rename() 仅适用于程序运行的目录? [英] rename() only works for directory that program is running in?
问题描述
我试图重命名用户指定目录中的一堆文件,但它似乎只有在用户指定运行程序的目录时才有效.例如,从命令行运行时:
I am trying to rename a bunch of files in a user specified directory, but it only seems to be working when the user specifies the directory that the program is running from. For example, when running from the command line:
./a.out .NewName.txt"
将起作用,而
./a.out .. "NewName.txt"
将不起作用.是否有一个原因?顺便说一下,它在 Linux 上.
./a.out .. "NewName.txt"
will not work. Is there a reason for this? It's on Linux, by the way.
int main(int argc, char** argv){
char* dirpath = argv[1];
char* newName = argv[2];
DIR *d;
struct dirent *dir;
d = opendir(dirpath);
if (d){
while ((dir = readdir(d)) != NULL){
char* filename = dir->d_name;
if (rename(filename,newName) == 0){
printf("Renaming %s -> %s\n",filename,newName);
} else {
printf("Could not rename %s\n",filename);
}
}
}
closedir(d);
}
我也尝试过(从桌面外部运行程序时):
I have also tried (while running the program from outside of Desktop):
if (rename("~/Desktop/test.txt","~/Desktop/test2.txt") == 0){
printf("Renaming %s -> %s\n",filename,newName);
} else {
printf("Could not rename %s\n",filename);
}
它仍然失败.
推荐答案
虽然 readdir()
正在从另一个目录读取文件名,但您程序的当前目录仍在不同的位置.除非您使用目录路径(以及目标文件名)作为源文件名的前缀,否则您通常会尝试重命名当前目录中不存在的文件.
While readdir()
is reading file names from the other directory, your program's current directory is still in a different location. Unless you prefix the source file name with the path to the directory (and the destination file name too) you're trying to rename non-existent files in the current directory, in general.
在伪代码中:
dir = opendir(remote_directory)
foreach name from dir
rename "remote_directory/name" to "remote_directory/othername"
end for
请注意,如果 'remote_directory' 恰好是 .
,当前目录,则伪代码有效;您不需要对该代码进行特殊处理.
Note that the pseudo-code works if 'remote_directory' happens to be .
, the current directory; you don't need to special-case that code.
这篇关于rename() 仅适用于程序运行的目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!