rename() only works for directory that program is running in?

核能气质少年 提交于 2020-01-07 05:12:11

问题


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" will work, while

./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);
 }

and it still fails.


回答1:


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.

In pseudo-code:

dir = opendir(remote_directory)
foreach name from dir
    rename "remote_directory/name" to "remote_directory/othername"
end for

Note that the pseudo-code works if 'remote_directory' happens to be ., the current directory; you don't need to special-case that code.




回答2:


I believe that your main problem is that the result from readdir is just the filename. It doesn't include the directory. You need to paste the directory name and the filename from dir->d_name together in your program.




回答3:


From the documentation:

The old argument points to the pathname of the file to be renamed. The new argument points to the new pathname of the file. If the new argument does not resolve to an existing directory entry for a file of type directory and the new argument contains at least one non-<slash> character and ends with one or more trailing <slash> characters after all symbolic links have been processed, rename() shall fail

Looks like you're not referring to an existing element when you use any path other than '.', which is likely why it's failing.

Check the specific errno value to see why.



来源:https://stackoverflow.com/questions/24744354/rename-only-works-for-directory-that-program-is-running-in

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!