How to check whether a File exists [duplicate]
Asked Answered
D

3

9

I have an Array of Strings and I want to select only these Strings which are paths to files:

My path is "~/dlds/some_file.ics" where ~/dlds is a symlink to ~/archive/downloads on my system. The file has following permissions:

-rw-r--r--

My code (I tried several variants):

ARGV.select do |string|
    File.file? string # returns false
    Pathname.new(string).file? # returns false
    Pathname.new(string).expand_path.file? # returns false
end

I don't know what else to try.

I'm running Ruby 2.2.0 or 2.2.2.

Dandridge answered 30/9, 2015 at 7:54 Comment(3)
Show your ARGV pleaseAllotment
I think the reason is in the ~/ directory. To check it try to pass the full path ie /home/user/dlds/some_file.icsAllotment
ARGV: ["--debug", "~/dlds/some_file"]. Using a full path doesn't work as well..Dandridge
C
17
File.exist? File.expand_path "~/dlds/some_file.ics"
Crompton answered 30/9, 2015 at 8:11 Comment(1)
note this returns true if the path is also a directory. details here: #8590598Amari
E
1

Your question is a bit confusing. If you want to check if the file exists, you should just do as you did:

Pathname.new(file_name).file? 

If you are using the ~ you will first have to expand the path, so write:

Pathname.new(file_name).expand_path.file? 

If you want to check if the given file_name is a symlink, you can just do

Pathname.new(file_name).expand_path.symlink? 

If you want to find the file the symlink points to, you have to follow the link:

File.readlink(Pathname.new(file_name).expand_path) 

which will return the filename of the linked file, so if you really wanted you could do something like:

Pathname.new(File.readlink(Pathname.new(file_name).expand_path)).file? 

to make sure the symlink is pointing to an existing file.

Electrotherapeutics answered 30/9, 2015 at 8:14 Comment(0)
R
0

I think File.readlink is what you are looking for

Returns the name of the file referenced by the given link. Not available on all platforms.

File.readlink("path/to/symlink")
Ruthy answered 30/9, 2015 at 7:57 Comment(3)
Results in Errno::ENOENT: No such file or directory @ rb_readlink - ~/dlds/some_fileDandridge
This should work. From the error you show you supplied the incorrect filename.Electrotherapeutics
The filename was auto-completed when I tried in irb, so no, I know that the file exists and the path is correct.Dandridge

© 2022 - 2024 — McMap. All rights reserved.