How can I gain permission to rename a file for my Ruby program?
As per the answer to this question, I am trying to backup a file by renaming it, before I replace it with a new, modified file with the old name.
开发者_开发技巧As per the comments and the documentation here, I am using the following line of code:
File.rename(File.basename(modRaw), File.basename(modRaw)+'.bak')
However, when I do so, I get the following error at runtime:
The program then aborts. (leatherReplacer.rb is the name of my program, and line 88 is the above line of code)
How do I allow my program to rename the files it needs to to run successfully?
Windows has some special rules regarding permissions. The important one at work here, is that the OS prevents moving or renaming a file while the file is open.
Depending on the nature of your code (in size and scope) and the importance of the file you're trying to back up, it may be unfeasible or otherwise not worthwhile to refactor the code in such a way as to make backups possible.
You probably don't want to be calling File.basename
in there, that strips off the directory:
Returns the last component of the filename given in *file_name*, which must be formed using forward slashes ("/") regardless of the separator used on the local file system.
So, if modRaw
is /where/is/pancakes.house
, then you're saying:
File.rename('pancakes.house', 'pancakes.house.bak')
But pancakes.house
probably isn't in the script's current directory. Try without the File.basename
calls:
File.rename(modRaw, modRaw + '.bak')
If you are owner of that file, use File.chmod to set desired permissions.
I don't know much about ruby, but could you run it under command line/bash with admin privileges, such as "run as administrator" or "su root"?
According to Objectmix and ruby-forum, you should set it to 755 or +x, then perhaps chown to yourself.
try using full file path e.t File.rename('c:\pancakes.house', 'c:\pancakes.house.bak')
in win7 i encounter same problem
精彩评论